I'm trying to understand C# async/await and observed this confusing behavior where async methods don't execute past Task.Delay
calls.
Consider the below -
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.MakeBreakfast();
}
public async Task MakeBreakfast()
{
await BoilWater();
StartToaster();
PutTeainWater();
PutBreadinToaster();
SpreadButter();
}
public async Task BoilWater() { Console.WriteLine("BoilWater start"); await Task.Delay(30); Console.WriteLine("BoilWater end"); }
public async Task StartToaster() { Console.WriteLine("StartToaster start"); await Task.Delay(1); Console.WriteLine("StartToaster end"); }
public async Task PutBreadinToaster() { Console.WriteLine("PutBreadinToaster start"); await Task.Delay(2000); Console.WriteLine("PutBreadinToaster end"); }
public async Task PutTeainWater() { Console.WriteLine("PutTeainWater start"); await Task.Delay(30); Console.WriteLine("PutTeainWater end"); }
public async Task SpreadButter() { Console.WriteLine("SpreadButter start"); await Task.Delay(10); Console.WriteLine("SpreadButter end"); }
}
Its output will be -
Boilwater Start Press any key to continue...
What happened to "Boilwater end" statement and all other method calls? If I put async/await only in the BoilWater method, I get the same output.
If I remove await from all method calls -
public async Task MakeBreakfast()
{
BoilWater();
StartToaster();
PutTeainWater();
PutBreadinToaster();
SpreadButter();
}
Now, the output is - BoilWater start StartToaster start PutTeainWater start PutBreadinToaster start SpreadButter start Press any key to continue . . .
Now, what happened to "end" statements? What's going on with async await in these examples?