Await for list of Tasks

C#.NetTask Parallel-LibraryAsync Await

C# Problem Overview


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

C# Solutions


Solution 1 - C#

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

Solution 2 - C#

You are looking for [Task.WaitAll][1] (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:

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

TaskList.WaitAll();

But that's really only syntactic sugar. [1]: http://msdn.microsoft.com/en-us/library/dd270695.aspx

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionctlaltdefeatView Question on Stackoverflow
Solution 1 - C#Stephen ClearyView Answer on Stackoverflow
Solution 2 - C#Simon BelangerView Answer on Stackoverflow