Are there good rule(s) for when to use Task.Delay versus Thread.Sleep?
- Specifically, is there a minimum value to provide for one to be effective/efficient over the other?
- Lastly, since Task.Delay causes context-switching on a async/await state machine, is there an overhead of using it?
Use
Thread.Sleep
when you want to block the current thread.Use
Task.Delay
when you want a logical delay without blocking the current thread.Efficiency should not be a paramount concern with these methods. Their primary real-world use is as retry timers for I/O operations, which are on the order of seconds rather than milliseconds.
if the current thread is killed and you use
Thread.Sleep
and it is executing then you might get aThreadAbortException
. WithTask.Delay
you can always provide a cancellation token and gracefully kill it. Thats one reason I would chooseTask.Delay
. see http://social.technet.microsoft.com/wiki/contents/articles/21177.visual-c-thread-sleep-vs-task-delay.aspxI also agree efficiency is not paramount in this case.
I want to add something. Actually,
Task.Delay
is a timer based wait mechanism. If you look at the source you would find a reference to aTimer
class which is responsible for the delay. On the other handThread.Sleep
actually makes current thread to sleep, that way you are just blocking and wasting one thread. In async programming model you should always useTask.Delay()
if you want something(continuation) happen after some delay.The biggest difference between
Task.Delay
andThread.Sleep
is thatTask.Delay
is intended to run asynchronous. It does not make sense to useTask.Delay
in synchronous code. It is a VERY bad idea to useThread.Sleep
in asynchronous code.Normally you will call
Task.Delay()
with theawait
keyword:or, if you want to run some code before the delay:
Guess what this will print? Running for 0.0070048 seconds. If we move the
await wait
above theConsole.WriteLine
instead, it will print Running for 5.0020168 seconds.Let's look at the difference with
Thread.Sleep
:Try to predict what this will print...
Also, it is interesting to notice that
Thread.Sleep
is far more accurate, ms accuracy is not really a problem, whileTask.Delay
can take 15-30ms minimal. The overhead on both functions is minimal compared to the ms accuracy they have (useStopwatch
Class if you need something more accurate).Thread.Sleep
still ties up your Thread,Task.Delay
release it to do other work while you wait.