Different behavior async/await in almost the same methods

后端 未结 4 1647
粉色の甜心
粉色の甜心 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:28

    In the second method 2 tasks are started at the same time. They will both finish in 2 seconds (as they are running in parallel). In the first method you first run one method (2 seconds), wait for it to complete, then start the second one (2 more seconds). The key point here is Task.Delay(..) starts right when you call it, not when you await it.

    To clarify more, first method:

    var t1 = Task.Delay(2000); // this task is running now
    await t1; // returns 2 seconds later
    var t2 = Task.Delay(2000); // this task is running now
    await t2; // returns 2 more seconds later
    

    Second method:

    var t1 = Task.Delay(2000); 
    var t2 = Task.Delay(2000); // both are running now
    
    await t1; // returns in about 2 seconds
    await t2; // returns almost immediately, because t2 is already running for 2 seconds
    

提交回复
热议问题