Does 'await Task.Delay(1000)' block ANY thread?

I've read that Task.Delay() is advised to be awaited not to block the calling thread (as oposed to Task.Delay().Wait() and Thread.Sleep()). But as I learned more about async/await I got a feeling that all it does is shifting the awaitable task for an execution on another thread.

So, did I understand it correctly: await Task.Delay() does not block the calling thread, however it blocks SOME thread, where the awaited task gets shifted to?

If that statement IS TRUE, then could you advice me on a method that asks a task to wait for a while WITHOUT blocking any thread during the wait?

Jon Skeet
people
quotationmark

however it blocks SOME thread, where the awaited task gets shifted to?

It depends on what you mean by "block". It doesn't cause any thread to go to sleep for 1 second, or (worse) spin wait for the delay to complete. Instead, it effectively schedules a timer to fire in 1 second, and then executes the continuation that will have been registered due to the await.

At a somewhat simplified level, await just translates to:

  • Call GetAwaiter on the awaitable, to get an awaiter
  • Check whether the awaiter has already completed - if so, just continue
  • Otherwise, schedule a continuation with the awaiter, and return
  • When the awaiter completes, the continuation is called and the async method continues

The clever bit is the way that the compiler saves state and manages the continuation so that it continues from the end of the await expression.

people

See more on this question at Stackoverflow