8

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?

1

2 Answers 2

16

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.

Sign up to request clarification or add additional context in comments.

4 Comments

So as I get it, the the thread where the awaited Delay() task gets sent to can be used to process other tasks, while Delay() is under way?
@cubrman: What do you mean by "where the awaited Delay() task gets sent"? Delay() returns a Task, and that task is completed a second later... it's not like this is a task which is actually doing anything. If you're comfortable with how System.Timers.Timer works (or similar) it's like that.
@cubrman The "Delay" does not happen on process. It happens on a piece of hardware called a clock/timer. It does not in anyway take resources from the program logic part of the CPU.
@cubrman Your question is like asking "When I set my alarm clock for the morning, which part of my brain does the checking "task" of when to wake up?"
0

So as I get it, the the thread where the awaited Delay() task gets sent to >can be used to process other tasks, while Delay() is under way? – cubrman Aug >15 at 10:19

No, you cannot do other things while you await for task.delay. The instruction below won't get executed, but the thread won't be blocked too! This means interface processing will still be working, you would be able for example move the mouse , click buttons etc.

1 Comment

But you can start the Task, do something, and await it after that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.