While commenting on an answer in this other SO post, the point came up that use of the Thread.Sleep() method is a code smell.
I have a hard time believing there is no use of this method that doesn’t indicate that you’re doing something wrong. I can think of a couple off the top of my head:
- Programmatically closing other applications; unless you want to kill the app (sometimes even then) you need to wait a few seconds for it to terminate gracefully.
- .NET 2.0 code: yes, it still exists. Thread.Yield() wasn’t invented until .NET 4, so if you want to let other applications do their thing while you’re stuck in some polling loop, a Thread.Sleep() for a short interval is the way to do it.
So, why would Thread.Sleep be such a terrible line of code to use in any circumstance that it would smell so?
I think you misunderstand what a code smell is. A code smell is something that is frequently misused or that tends to suggest a poor design. It means you should investigate it, not that you should avoid it!
Thread.Sleep often indicates that a thread is waiting for something but has no way to know how long it should wait. That usually indicates that a control function that should be closed loop is instead implemented as an open loop.
It is also sometimes used as a broken way to increase fairness. But fairness is generally bad because it has costs (extra context switches at a minimum) and it’s not like your threads will file union grievances. There is generally no reason to be fair to them since they’re all cooperating to get work done.
Of course if it’s the best way to get a job done, or the good enough in a case where other solutions would require more effort or entail higher risk, you should use it.