To my understanding a Thread.Sleep(0) force a context switch on the OS.
I wanted to check what was the maximum amount of time that could pass in an application befor
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.