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?
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.
Task. Delay() is asynchronous. It doesn't block the current thread. You can still do other operations within current 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.
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.
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:
GetAwaiter
on the awaitable, to get an awaiterThe 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With