EN
C#/.NET - thread yield method example
16 points
In this article, we would like to explain how Thread.Yield()
method works on C# / .NET example.
When we write programs that use 100% of processor load it is necessary to yield processor execution between threads. The problem of load dispatching is solved by Thread.Yield()
method.
In this section, we have created many threads with infinity loops to get high processor load, dispatching load between threads by Thread.Yield()
method calls.
xxxxxxxxxx
1
using System;
2
using System.Threading;
3
4
namespace Test
5
{
6
class Program
7
{
8
public static void Main(string[] args)
9
{
10
int count = 5 * Environment.ProcessorCount; // increase it if needed
11
12
for (int i = 0; i < count; ++i)
13
{
14
Thread thread = new Thread(() =>
15
{
16
while (true) // 100% load for single processor
17
{
18
Thread.Yield(); // Thread.Sleep() method can be used too
19
}
20
});
21
22
thread.Start();
23
}
24
25
{
26
Thread thread = new Thread(() =>
27
{
28
Thread.Sleep(2000);
29
30
Console.WriteLine("Message after 2000 ms...");
31
});
32
33
thread.Start();
34
}
35
}
36
}
37
}
Output:
xxxxxxxxxx
1
Message after 2000 ms...
This section uses a similar program to the above, but without Thread.Yield()
method calls. That approach should never let dispatch load between different threads.
xxxxxxxxxx
1
using System;
2
using System.Threading;
3
4
namespace Test
5
{
6
class Program
7
{
8
public static void Main(string[] args)
9
{
10
int count = 5 * Environment.ProcessorCount;
11
12
for (int i = 0; i < count; ++i)
13
{
14
Thread thread = new Thread(() =>
15
{
16
while (true); // 100% load for single processor without yield !!!
17
});
18
19
thread.Start();
20
}
21
22
{
23
Thread thread = new Thread(() =>
24
{
25
Thread.Sleep(2000);
26
27
Console.WriteLine("Message after 2000 ms...");
28
});
29
30
thread.Start();
31
}
32
}
33
}
34
}
Output:
xxxxxxxxxx
1
Summary:
Avoided
Thread.Yield()
method in last thread causes the thread probably will never get processor time to print the message.