I clearly understand TAP model execution in C#. However, when it comes to concurrent tasks I get confused.
Consider this example in MS docs:
Coffee cup = PourCoffee();
Console.WriteLine("Coffee is ready");
Task<Egg> eggsTask = FryEggsAsync(2);
Task<Bacon> baconTask = FryBaconAsync(3);
Task<Toast> toastTask = ToastBreadAsync(2);
Toast toast = await toastTask;
ApplyButter(toast);
ApplyJam(toast);
Console.WriteLine("Toast is ready");
Juice oj = PourOJ();
Console.WriteLine("Oj is ready");
Egg eggs = await eggsTask;
Console.WriteLine("Eggs are ready");
Bacon bacon = await baconTask;
Console.WriteLine("Bacon is ready");
Console.WriteLine("Breakfast is ready!");
Calling async
without await
ing it's just very confusing.
Let's take this line for example: Task<Egg> eggsTask = FryEggsAsync(2);
1- Main thread will call the function and start executing it.
2- When the main thread counters the first await
it will return to the Main()
function.
Now, when the await Task.Delay(3000);
in the FryEggsAsync()
completes what is happening?
private static async Task<Egg> FryEggsAsync(int howMany)
{
Console.WriteLine("Warming the egg pan...");
await Task.Delay(3000);
Console.WriteLine($"cracking {howMany} eggs");
Console.WriteLine("cooking the eggs ...");
await Task.Delay(3000);
Console.WriteLine("Put eggs on plate");
return new Egg();
}
I tried to debug this example with Rider and I got that when the await Task.Delay(3000);
completes FryEggsAsync()
spawn thread from the thread pool and continue execution with it.
Does that mean that each of the three functions will continue the execution in the background with threads from the pool without the need to continue it on the main thread?
Or the function is suspended at the await
line and doesn't proceed until I await
it from the Main()
function?