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