I've was playing around with async and I've happened across some behaviour I've not noticed before, if this is a duplicate please let me know, but my google-fu has failed me, mostly because I can't think of decent terms to search:
Given a simple async method that does some parameterized work:
async Task<String> Foo(int i)
{
await Task.Delay(i);
return i.ToString();
}
And a calling method to invoke it in different contexts and bundle the result:
async Task<Object> Bar()
{
var one = Foo(3000);
var two = Foo(5000);
var three = Foo(3000);
var x =
new
{
One = await one,
Two = await two,
Three = await three,
};
return x;
}
This completes (in Linqpad6, .NET Core 3.1) in 5 seconds. So I assume each task runs at the same time.
However, if I change it to do the await at the start, it completes in 11 seconds. So I assume each task runs sequentially.
async Task<Object> Bar()
{
var one = await Foo(3000);
var two = await Foo(5000);
var three = await Foo(3000);
var x =
new
{
One = one,
Two = two,
Three = three,
};
return x;
}
My question is, what is it about assigning the task, then awaiting it, versus just awaiting it that allows them to complete in parallel?