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")
WhenAll(Task[])Creates a task that will complete when all of the Task objects in an array have completed.
WhenAll creates a task that will complete when all of the supplied tasks have been completed. It's pretty straightforward what this method does, it simply receives a list of Tasks and returns a Task when all of the received Tasks completes.
If you don't await the task or explicitly check for exceptions, the exception is lost. If you await the task, its exception is rethrown. As a best practice, you should always await the call. By default, this message is a warning.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With