Languages
[Edit]
EN

C#/.NET - thread yield method example

13 points
Created by:
Marcin
15740

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.

References

  1. Thread.Yeld Method - Microsoft Docs
Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join