Reputation: 21
Both Thread.Sleep()
and Task.Delay()
can suspend the execution of a program (thread) for a given timespan. But are there actually suspending the execution? What is the difference? Hopefully some one can trying to answer all the questions above.
Upvotes: 0
Views: 140
Reputation: 456322
Thread.Sleep
is a blocking call. It puts the current thread into a wait state until the timeout period elapses. So yes, Thread.Sleep
does suspend the current thread.
Task.Delay
also uses a timer, but it does not block. Instead, it returns a Task
that completes when that timer fires. So it does not suspend the current thread.
Task.Delay
is commonly used with await
, which will suspend the current method (not thread). The thread returns from that method and continues executing.
So, Thread.Sleep
suspends the current thread (and the method it's executing), but await Task.Delay
will suspend the current method without suspending the current thread.
Upvotes: 3