为什么分配任务然后等待它可以并行运行 [英] Why does assigning a Task then awaiting it allow to run in parallel
问题描述
我一直在玩异步程序,并且遇到了一些以前未曾发现的行为,如果这是重复行为,请告诉我,但是我的google-fu让我失败了,主要是因为我可以不要想到要搜索的体面术语:
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;
}
这将在5秒钟内完成(在Linqpad6,.NET Core 3.1中).因此,我假设每个任务都同时运行.
This completes (in Linqpad6, .NET Core 3.1) in 5 seconds. So I assume each task runs at the same time.
但是,如果我将其更改为在开始时进行等待,则它将在11秒内完成.因此,我假设每个任务都按顺序运行.
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?
推荐答案
查看注释行
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;
}
这篇关于为什么分配任务然后等待它可以并行运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!