Given this code... Why will Main1() take ~ 1 second but Main2() only 500 ms?
Why does it make a difference to store the Task in a variable first and awaiting then?
async Task Main1()
{
await DoStuff(1);
await DoStuff(2);
}
async Task Main2()
{
var t1 = DoStuff(1);
var t2 = DoStuff(2);
await t1;
await t2;
}
async Task DoStuff(int number)
{
await Task.Delay(500);
Console.WriteLine(number);
}
It's not about whether you store the tasks in variables, it's about when you start the tasks. In this case:
async Task Main1()
{
await DoStuff(1); // Task 1
await DoStuff(2); // Task 2
}
You start task 2 after you wait for task 1 to finish. Note that calling DoStuff starts the task, and await wait for it to finish.
In this case:
async Task Main2()
{
var t1 = DoStuff(1); // Task 1
var t2 = DoStuff(2); // Task 2
await t1;
await t2;
}
You start task 2 without waiting for task 1 to finish, so they are executed asynchronously.
If you did this instead:
async Task Main3()
{
var t1 = DoStuff(1);
await t1;
var t2 = DoStuff(2);
await t2;
}
You would get the same behaviour as Main1. This shows that whether or not you put the task into variables doesn't matter.
In Main1, DoStuff(2) get started only when DoStuff(1) is done.
But in Main2, both t1 and t2 task start almost at same time and are handled concurrently.