EN
C#/.NET - thread yield method example
13
points
During writing of programs that have 100% of processor load it is necessary to yield processor execution between threads. The problem of load dispatching is solved by Thread.Yield
method.
1. Thread.Yield
method example
using System;
using System.Threading;
namespace Test
{
class Program
{
public static void Main(string[] args)
{
int count = 5 * Environment.ProcessorCount;
for (int i = 0; i < count; ++i)
{
Thread thread = new Thread(() =>
{
while (true) // 100% load for single processor
{
Thread.Yield();
// Thread.Sleep method can be used too
}
});
thread.Start();
}
{
Thread thread = new Thread(() =>
{
Thread.Sleep(2000);
Console.WriteLine("Message after 2000 ms...");
});
thread.Start();
}
}
}
}
Output:
Message after 2000 ms...
Note: number of threads (count
variable in above program) should be enough big to do not let work all threads in same time to show the problem.
2. Incorrect program example - similar to above program
using System;
using System.Threading;
namespace Test
{
class Program
{
public static void Main(string[] args)
{
int count = 5 * Environment.ProcessorCount;
for (int i = 0; i < count; ++i)
{
Thread thread = new Thread(() =>
{
while (true); // 100% load for single processor without yield !!!
});
thread.Start();
}
{
Thread thread = new Thread(() =>
{
Thread.Sleep(2000);
Console.WriteLine("Message after 2000 ms...");
});
thread.Start();
}
}
}
}
Output:
Note: Lack of Thread.Yeld
method execution causes, the printing message thread probably will never get processor time to print message.