Echo
Echo

Reputation: 21

Await vs await Task.Delay trying to learn

If I have code that says:

public async Task Test1()
{
    Task task1 = MakeEggAsync();
    Task task2 = MakeBaconAsync();

    await Task.WhenAll(task1, task2);

}

async Task MakeBaconAsync()
{
    while (CookIsBusy)
    {
        //      
        await Task.Delay(100);
    }
}

async Task MakeEggAsync()
{
    await makeEgg2Async();
}

async Task makeEgg2Async()
{

    while (CookIsBusy)
    {
        //      
        await Task.Delay(100);
    }
}

...will the computer return to the main Test1() after it get to this line?

async Task MakeEggAsync()
{
    await makeEgg2Async();
}

...or will it return only after it get to a delay? I know with threading it only returns after you get to a wait. Sorry I am new to this and I am trying to learn.

Does the computer returns after it gets to an await or after it get to a Task.Delay? This is what I am really asking.

Upvotes: 0

Views: 67

Answers (1)

Stephen Cleary
Stephen Cleary

Reputation: 457472

Every async method begins executing synchronously.

Also, objects are awaited, not methods. In other words, this code:

async Task  MakeEggAsync()
{
  await makeEgg2Async();
}

is roughly the same as this code:

async Task  MakeEggAsync()
{
  var task = makeEgg2Async();
  await task;
}

So the computer returns to Test1 after the Task.Delay is invoked.

Upvotes: 1

Related Questions