问题描述
我有这样的创建任务列表:
I have a list of tasks that I created like this:
public async Task<IList<Foo>> GetFoosAndDoSomethingAsync()
{
var foos = await GetFoosAsync();
var tasks = foos.Select(async foo => await DoSomethingAsync(foo)).ToList();
...
}
通过使用 .ToList()
,这些任务都应该开始。现在我想等待他们完成并返回结果。
By using .ToList()
, the tasks should all start. Now I want to await their completion and return the results.
这工作在上述 ...
块:
var list = new List<Foo>();
foreach (var task in tasks)
list.Add(await task);
return list;
据我想要做什么,但这似乎相当笨拙。我宁愿写这样简单的东西:
It does what I want, but this seems rather clumsy. I'd much rather write something simpler like this:
return tasks.Select(async task => await task).ToList();
...但是这不能编译。我在想什么?或只是无法前preSS事情这样?
... but this doesn't compile. What am I missing? Or is it just not possible to express things this way?
推荐答案
LINQ不异步 code完全符合工作,但你可以这样做:
LINQ doesn't work perfectly with async
code, but you can do this:
var tasks = foos.Select(DoSomethingAsync).ToList();
await Task.WhenAll(tasks);
如果您的任务都返回相同类型的值,那么你甚至可以做到这一点:
If your tasks all return the same type of value, then you can even do this:
var results = await Task.WhenAll(tasks);
这是相当不错的。 WhenAll
返回一个数组,所以我相信你的方法可以直接返回结果:
which is quite nice. WhenAll
returns an array, so I believe your method can return the results directly:
return await Task.WhenAll(tasks);
这篇关于如何等待异步使用LINQ的任务列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!