J. Doe
J. Doe

Reputation: 129

Thread.Sleep(0) vs Thread.Sleep(1) vs Thread.Sleep(2)

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?

Upvotes: 2

Views: 1059

Answers (1)

Clint
Clint

Reputation: 6509

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

Upvotes: 5

Related Questions