Is Sleep() evil?

First of all, there are many cases where Sleep() is misused, for example to "synchronize" threads or to regularily poll a value where a notification function would do (In Win32 WaitForSingleObject for example)

But what about other use cases? Is Sleep always evil? If no, what are good use cases for Sleep? If yes, why do almost all languages have some kind of Sleep statement?

PS: I've asked this question because of one of the comments of another question. There the OP states, that in his opinion, Sleep is to be avoided like goto.


I actually believe the assertion you linked is correct. The problem is sleep is being used (as you noted) as an inefficient substitute for notification mechanisms. Sleep is always inferior to a properly implemented notification mechanism, If you are waiting for an event. If you actually need to wait a specific amount of time for something, then sleep is appropriate.

For example, in some network protocols, you make use of a technique known as exponential backoff, where if you detect a collision on the network, you want to wait a random (and exponentially increasing) amount of time before you retry. In this case sleep is appropriate because you're not trying to wait for an event to happen, you're trying to wait for a specific amount of time to pass.


Ive found a good use for using Thread.Sleep(1000); to simulate latency when writing a callback in a web application.

A simple example with Microsoft's AJAX components is to put a button in an update panel... on the onclick handler use Thread.Sleep(), the update progress panel will then display for that amount of time.

Obvously remove the Thread.Sleep() when going live... :)


In the real world, it's not always practical to use the proper synchronisation primitives:

  • Sometimes you need to poll something until a condition is met, and there you use sleep to avoid soaking the machine.

  • Sometimes you actively want to sleep - for instance, when you want a thread to take minimal machine resources and you're on an operating system (cough Windows cough) that doesn't do a very good job of preventing low-priority threads from soaking the machine.

Edit in response to Kieveli's comment: I think you should implement proper signalling when you can. So a worker thread should do a blocking read on a queue rather than sleeping and polling. I'm saying that sometimes you're forced to interact with systems that preclude doing the right thing. I'm not saying you shouldn't bother doing the right thing when it's reasonably possible - "within half a second is good enough", maybe, but near-instantaneous would be noticeably better!