Why does assigning a Task then awaiting it allow to run in parallel

Viewed 123

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?

1 Answers

See comments in line

async Task<Object> Bar()
{
    var one =    Foo(3000); // <-- It can Start
    var two =    Foo(5000); // <-- It can Start
    var three =  Foo(3000); // <-- It can Start

    var x =
        new
        {
            One =   await one,  // <-- you are waiting for it to finish
            Two =   await two,  // <-- you are waiting for it to finish
            Three = await three,// <-- you are waiting for it to finish
        };      
        
    return x;
}

async Task<Object> Bar()
{
    var one =   await Foo(3000); // <-- you are waiting for it to finish
    var two =   await Foo(5000); // <-- you are waiting for it to finish
    var three = await Foo(3000); // <-- you are waiting for it to finish

    var x =
        new
        {
            One =   one,
            Two =   two,
            Three = three,
        };
        
    return x;
}
Related