几乎相同的方法,不同的行为异步/等待 [英] Different behavior async/await in almost the same methods
问题描述
假设我有两种异步方法
public async static Task RunAsync1()
{
await Task.Delay(2000);
await Task.Delay(2000);
}
和
public async static Task RunAsync2()
{
var t1 = Task.Delay(2000);
var t2 = Task.Delay(2000);
await t1;
await t2;
}
然后我像这样使用它
public static void M()
{
RunAsync1().GetAwaiter().GetResult();
RunAsync2().GetAwaiter().GetResult();
}
结果是 RunAsync1
将运行 4sec ,但仅运行 RunAsync2
2sec
有人可以解释为什么吗?方法几乎相同。有什么区别?
In a result the RunAsync1
will run 4sec but RunAsync2
only 2sec
Can anybody explain why? Methods are almost the same. What is the difference?
推荐答案
在第二种方法中,同时启动2个任务。它们都将在2秒内完成(因为它们并行运行)。在第一种方法中,您首先运行一种方法(2秒),等待其完成,然后再启动第二种方法(再过2秒)。此处的关键是 Task.Delay(..)
是在您调用它时开始的,而不是在您等待时开始的。
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
第二种方法:
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
这篇关于几乎相同的方法,不同的行为异步/等待的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!