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.
Practical example
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.
using System;
using System.Threading;
namespace Test
{
class Program
{
public static void Main(string[] args)
{
int count = 5 * Environment.ProcessorCount; // increase it if needed
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...
Incorrect program example
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.
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:
Summary:
Avoided
Thread.Yield()
method in last thread causes the thread probably will never get processor time to print the message.