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

假装没事ソ 提交于 2020-11-29 09:17:05

问题


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:


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;
}


来源:https://stackoverflow.com/questions/64646361/why-does-assigning-a-task-then-awaiting-it-allow-to-run-in-parallel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!