Different behavior async/await in almost the same methods

后端 未结 4 1579
粉色の甜心
粉色の甜心 2021-01-17 09:59

Let\'s say I have two async methods

public async static Task RunAsync1()
{
    await Task.Delay(2000);
    await Task.Delay(2000);
}

and

4条回答
  •  有刺的猬
    2021-01-17 10:29

    In the first case you are saying

    public async static Task RunAsync1()
    {
        var t1 = Task.Delay(2000);
        await t1;
        var t2 = await Task.Delay(2000);
        await t2;
    }
    

    Which equates to

    1. 0:00 Create a callback in 2 seconds 0:00
    2. 0:00 Wait until the callback has returned 0:02
    3. 0:02 Create a callback in 2 seconds 0:02
    4. 0:02 Wait until the callback has returned 0:04
    5. 0:04 return;

    The second case is

    public async static Task RunAsync2()
    {
        var t1 = Task.Delay(2000);
        var t2 = Task.Delay(2000);
    
        await t1;
        await t2;
    }
    
    1. 0:00 Create callbacks in 2 seconds 0:00
    2. 0:00 Create callbacks in 2 seconds 0:00
    3. 0:00 Wait for first callback 0:02
    4. 0:02 Wait for the second callback 0:02
    5. 0:02 return

    In other words, in the first one you are doing sequential asynchronous programming, and the second is parallel asynchronous programming.

提交回复
热议问题