Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

C#/.NET - thread yield method example

0 contributions
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.

References

  1. Thread.Yeld Method - Microsoft Docs
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more