7

When we use await in the code, generally the awaiters capture the context and use that as callback when the awaited task completed successfully. But, since await is generally a No-Op (No Operation), does it make the underlying thread not being reusable until execution of the awaited task completes?

For Example:

public async Task MethodAAsync()
{
    // Execute some logic
    var test = await MethodB();
    // Execute remaining logic
}

Here, since I need the result back to proceed further, I need to await on that. But, since we are awaiting, does it block the underlying thread resulting thread not being used to execute any tasks?

janw
  • 8,758
  • 11
  • 40
  • 62

3 Answers3

11

But, since await is generally a No.Op(No Operation), does it make the underlying thread not being reusable until execution of awaited task completes?

I'm not sure where you got this information from, but await is certainly not a No-Op. Calling await on a Task, for example, will invoke a logical call to Task.GetAwaiter, where the TaskAwaiter has to implement INotifyCompletion or ICriticalNotifyCompletion interface, which tells the compiler how to invoke the continuation (everything after the first await).

The complete structure of async-await transforms your call to a state-machine such that when the state-machine hits the first await, it will first check to see if the called method completed, and if not will register the continuation and return from that method call. Later, once that method completes, it will re-enter the state-machine in order to complete the method. And that is logically how you see the line after await being hit.

But, since we are awaiting, does it block the underlying thread resulting thread not being used to execute any tasks?

No, creating an entire mechanism only to block the calling thread would be useless. async-await allow you to actually yield the calling thread back to the caller which allows him to continue execution on that same thread, while the runtime takes care of queuing and invoking the completion.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321
4

In short, no, it doesn't block your thread.

More info: http://blog.stephencleary.com/2013/11/there-is-no-thread.html

-1

The thread has a local queue of Tasks. Once it hits an await it will pick up another Task from it's queue (assuming all methods up it's stack are awaited). If the queue is empty, it will try to get a Task from the global queue, and if it's empty too - the thread will try to get a Task from another thread's own local queue. In a simple program, where all threads might get "out of Tasks" - the thread will remain idle until one of the Tasks returns.

shay__
  • 3,815
  • 17
  • 34