0

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.

Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
jack_jay
  • 21
  • 1
  • Take a look at https://stackoverflow.com/questions/20082221/when-to-use-task-delay-when-to-use-thread-sleep – Dominik May 16 '22 at 06:09
  • 2
    Does this answer your question? [When to use Task.Delay, when to use Thread.Sleep?](https://stackoverflow.com/questions/20082221/when-to-use-task-delay-when-to-use-thread-sleep) – Dominik May 16 '22 at 06:11
  • the problem is similar to [this question](https://stackoverflow.com/questions/37419572/if-async-await-doesnt-create-any-additional-threads-then-how-does-it-make-appl) – CF2096 May 16 '22 at 06:12
  • Does this answer your question? [Does the use of async/await create a new thread?](https://stackoverflow.com/questions/27265818/does-the-use-of-async-await-create-a-new-thread) – Charlieface May 16 '22 at 08:27
  • 3
    See also Stephen Cleary: [There Is No Thread](https://blog.stephencleary.com/2013/11/there-is-no-thread.html) – Charlieface May 16 '22 at 08:28
  • Related: [Thread.Sleep vs Task.Delay?](https://stackoverflow.com/questions/17258428/thread-sleep-vs-task-delay) – Theodor Zoulias May 16 '22 at 10:34

1 Answers1

3

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.

Stephen Cleary
  • 437,863
  • 77
  • 675
  • 810