C# 等待任务列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17621632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Await for list of Tasks
提问by ctlaltdefeat
I'm trying to do something like this:
我正在尝试做这样的事情:
foreach (var o in ObjectList)
{
CalculateIfNeedToMakeTaskForO(o);
if (yes)
TaskList.Add(OTaskAsync());
}
Now I would like to wait for all these tasks to complete. Besides doing
现在我想等待所有这些任务完成。除了做
foreach(var o in ObjectList)
{
Result.Add("result for O is: "+await OTaskAsync());
}
Is there anything I could do? (better, more elegant, more "correct")
有什么我可以做的吗?(更好,更优雅,更“正确”)
采纳答案by Simon Belanger
You are looking for Task.WaitAll(assuming your TaskListimplemented IEnumerable<Task>)
您正在寻找Task.WaitAll(假设您已TaskList实现IEnumerable<Task>)
Task.WaitAll(TaskList.ToArray());
Edit:Since WaitAllonly takes an array of task (or a list of Taskin the form of a variable argument array), you have to convert your Enumerable. If you want an extension method, you can do something like this:
编辑:由于WaitAll只需要一个任务数组(或Task一个可变参数数组形式的列表),你必须转换你的 Enumerable。如果你想要一个扩展方法,你可以这样做:
public static void WaitAll(this IEnumerable<Task> tasks)
{
Task.WaitAll(tasks.ToArray());
}
TaskList.WaitAll();
But that's really only syntactic sugar.
但这实际上只是语法糖。
回答by Stephen Cleary
You are looking for Task.WhenAll:
您正在寻找Task.WhenAll:
var tasks = ObjectList
.Where(o => CalculateIfNeedToMakeTaskForO(o))
.Select(o => OTaskAsync(o))
.ToArray();
var results = await Task.WhenAll(tasks);
var combinedResults = results.Select(r => "result for O is: " + r);

