I have just started learning "Threading in C#". I found in a book that Thread.Sleep(0) relinquishes the thread’s current time slice immediately, voluntarily handing over the CPU to other threads.
When I wrote few lines of code to test it. I did not get the expected result. Here the the code I wrote.
class Program
{
static void Main(string[] args)
{
Thread.CurrentThread.Name = "Thread A(main thread)";
Thread thread = new Thread(PrintNumber);
thread.Name = "Thread B";
thread.Start();
for (int i = 0; i < 40; i++)
{
Console.WriteLine("{0} | i = {1}", Thread.CurrentThread.Name, i);
}
}
void PrintNumber()
{
for (int i = 0; i < 40; i++)
{
Console.WriteLine("{0} | i = {1}", Thread.CurrentThread.Name, i);
if (i == 4)
{
Thread.Sleep(0);
}
}
}
}
According to my understanding this will print up to 4 in thread B then it will resume the thread A. Next thread schedule is unpredictable. But this is not happening. While it comes to thread B for the first time sometimes it prints upto 6 sometimes 8 means totally unpredictable.
So is my concept of Theread.Sleep(0) is wrong? Can someone please clarify the concept