Await for list of Tasks

2019-03-14 11:58发布

问题:

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")

回答1:

You are looking for Task.WaitAll (assuming your TaskList implemented IEnumerable<Task>)

Task.WaitAll(TaskList.ToArray());

Edit: Since WaitAll only takes an array of task (or a list of Task in 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:

pulic static void WaitAll(this IEnumerable<Task> tasks) 
{
    Task.WaitAll(tasks.ToArray());
}

TaskList.WaitAll();

But that's really only syntactic sugar.



回答2:

You are looking for 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);