Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple await operations or just one

I've seen how the await keyword is implemented and resulting structure it creates. I think I have a rudimentary understanding of it. However, is

public async Task DoWork()
{
    await this.Operation1Async();
    await this.Operation2Async();
    await this.Operation3Async();
}

"better" (generally speaking) or

public async Task DoWork()
{
    await this.Operation1Async();
    this.Operation2();
    this.Operation3();
}

The problem with the first approach is that it is creating a new Task for each await call? Which entails a new thread?

Whereas the first creates a new Task on the first await and then everything from there is processed in the new Task?

Edit Ok maybe I wasn't too clear, but if for example we have

while (await reader.ReadAsync())
{
    //...
}

await reader.NextResultAsync();

// ...

Is this not creating two tasks? One in the main thread with the first ReadAsync then another task in this newly created task with the NextResultAsync. My question is there really a need for the second task, isn't the one task created in the main thread sufficient? So

while (await reader.ReadAsync())
{
    //...
}

reader.NextResult();

// ...
like image 387
Umair Avatar asked Feb 07 '23 06:02

Umair


1 Answers

it is creating a new Task for each await call? Which entails a new thread?

Yes and no. Yes, it is creating a Task for each asynchronous method; the async state machine will create one. However, these tasks are not threads, nor do they even run on threads. They do not "run" anywhere.

You may find some blog posts of mine useful:

  • async intro, which explains how async/await work.
  • There Is No Thread, which explains how tasks can work without threads.
  • Intro to the Task type, which explains how some tasks (Delegate Tasks) have code and run on threads, but the tasks used by async (Promise Tasks) do not.

Whereas the first creates a new Task on the first await and then everything from there is processed in the new Task?

Not at all. Tasks only complete once, and the method will not continue past the await until that task is complete. So, the task returned by Operation1Async has already completed before Operation2 is even called.

like image 124
Stephen Cleary Avatar answered Feb 12 '23 12:02

Stephen Cleary