Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 752
cubrman Avatar asked Aug 15 '15 10:08

cubrman


People also ask

Does await block the thread?

Because await is only valid inside async functions and modules, which themselves are asynchronous and return promises, the await expression never blocks the main thread and only defers execution of code that actually depends on the result, i.e. anything after the await expression.

Does task delay use a thread?

Task. Delay() is asynchronous. It doesn't block the current thread. You can still do other operations within current thread.

Does await release thread?

An await expression in an async method doesn't block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method. The async and await keywords don't cause additional threads to be created.

Does task wait block?

If the current task has not started execution, the Wait method attempts to remove the task from the scheduler and execute it inline on the current thread. If it is unable to do that, or if the current task has already started execution, it blocks the calling thread until the task completes.


1 Answers

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.

like image 180
Jon Skeet Avatar answered Sep 23 '22 00:09

Jon Skeet