0

If I am not mistaken, Thread.Sleep(0) will relinquish the calling thread's timeslice to any other thread with priority equal or higher than the calling thread, while Thread.Sleep(any number larger than zero) will relinquish it to any waiting thread.

Now, something is swirling in the back of my mind that before C# 3 or 4, it used to be that Thread.Sleep(0) would relinquish to only higher priority threads, Thread.Sleep(1) to higher priority or same priority and Thread.Sleep(2) to any priority. Am I right?

J. Doe
  • 99
  • 1
  • 6

1 Answers1

3

Thread.Sleep(n); // Where n is milliseconds

When N==0

This tells the system you want to forfeit the rest of the thread’s timeslice and let another waiting thread (whose priority >= currentThread) run (this means you won't be sure when you get your control back).
If there are no other threads of equal priority that are ready to run, execution of the current thread is not suspended.

When N>=1 (be it N=1 or N=2)

Will block the current thread for at least the number of timeslices (or thread quantums) that can occur within n milliseconds, In other words it will relinquish the remainder of its time slice to any other thread un-conditionally.

The Windows thread scheduler ensures that each thread (at least those with the same priority) will get a fair slice of CPU time to execute. The reason for blocking the current thread for atleast specified interval is because scheduler might take longer than the specified interval before it gets around to that thread again.

References: 1, 2, 3


Update

In my pursuit to find the working of Sleep in versions prior to C# 3, I've come across interesting articles (on and before year 2005) that I felt is worth an update.

In short, I did not find any difference with regards to threads relinquishing to higher or same priority when n=1 or n=2.

From Vaults: 1, 2, 3

Clint
  • 6,011
  • 1
  • 21
  • 28
  • Careful, "thread quantum" means something very different on Windows. It is for example 3 ticks on the workstation version for a thread that owns the foreground window. As long as it can run before being pre-emptively switched out. Thread.Sleep() has tick accuracy. – Hans Passant Mar 14 '20 at 15:56
  • Thanks, but do you have any idea if it was different in the ol' days? Specifically before C# 3? – J. Doe Mar 14 '20 at 16:17
  • 1
    hey @J.Doe, I've been digging through the old vaults to validate your query, from what I gather I don't find it any different. Let me update the answer with my findings – Clint Mar 15 '20 at 02:56