1

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

Amitava Karan
  • 637
  • 1
  • 5
  • 20
  • I found the this thread while searching. I overlooked on it and thought it describes different problem. Now I see it asks almost same question as of mine. Sorry for the repetition. – Amitava Karan Nov 08 '13 at 09:11

2 Answers2

3

If it does free up the thread's slice, that doesn't mean you can predict where it is going - it could go to any process on the computer. In particular, assuming you have a multi-core machine, the other thread could be being serviced entirely by another core. In the code as shown, it is also likely that "Thread B" doesn't even get started until the near of Main's loop. Starting a thread is not instantaneous.

There are very few scenarios where Thread.Sleep(0) is going to be useful to you, and all of those scenarios would involve extensive knowledge of threading and memory models.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
2

Thread.Yield() ensures that the next thread being executed is not the current thread.

Michael Mairegger
  • 6,833
  • 28
  • 41