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.WhenAll
:You are looking for
Task.WaitAll
(assuming yourTaskList
implementedIEnumerable<Task>
)Edit: Since
WaitAll
only takes an array of task (or a list ofTask
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:But that's really only syntactic sugar.