问题描述
我有一个像这样创建的任务列表:
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.
这适用于上面的 ...
块:
This works in the above ...
block:
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();
...但这不能编译.我错过了什么?还是只是不能这样表达?
... but this doesn't compile. What am I missing? Or is it just not possible to express things this way?
推荐答案
LINQ 不能与 async
代码完美配合,但您可以这样做:
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 异步等待任务列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2