Thread.Sleep(0) : What is the normal behavior? Thread.Sleep(0) : What is the normal behavior? windows windows

Thread.Sleep(0) : What is the normal behavior?


It doesn't force a context switch, only Sleep(1) does that. But if there's any other thread from any process ready to run and has a higher priority then Sleep(0) will yield the processor and let it run. You can see this by running an endless loop that calls Sleep(0), it will burn 100% CPU cycles on one core. I don't understand why you don't observe this behavior.

The best way to keep the system responsive is by giving your thread a low priority.


My understanding is that Thread.Sleep(0) does not force a thread context switch, it simply signals the task scheduler that you are willing to give up the rest of your time slice if there are other threads waiting to execute.

Your loop around Sleep(0) is chewing up CPU time, and that will have a negative effect on other applications (and laptop battery life!). Sleep(0) doesn't mean "let everything else execute first", so your loop will be competing for execution time with other processes.

Passing a non-zero wait time to Sleep() would be marginally better for other apps because it would actually force this thread to be put aside for a minimum amount of time. But this is still not how you implement a minimum-impact background thread.

The best way to run a CPU bound background thread with minimum impact to foreground applications is to lower your thread priority to something below normal. This will tell the scheduler to execute all normal priority threads first, and if/when there is any other time available then execute your low priority thread. The side effect of this is that sometimes your low priority thread may not get any execution time at all for relatively long periods of time (seconds) depending on how saturated the CPU is.


I was bitten by this bug in a previous project. I had a thread running which would check messages in a prioritized queue, looking for a new one. If it found no new message, I wanted the thread to go to sleep until a message's being added to the queue would wake it back up to check again.

Naively, assuming that Thread.Sleep(0) would cause the thread to go to sleep until woken up again, I found our app consuming crazy amounts of CPU once messages started coming in.

After a few days of sleuthing possible causes, we found the info from this link. The quick fix was to use Thread.Sleep(1). The link has the details around the reason for the difference, including a little test app at the bottom, demonstrating what happens to performance between the 2 options.