Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Await for list of Tasks

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

like image 688
ctlaltdefeat Avatar asked Jul 12 '13 18:07

ctlaltdefeat


People also ask

What is the use of task WhenAll?

WhenAll(Task[])Creates a task that will complete when all of the Task objects in an array have completed.

Does task WhenAll start the tasks?

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.

What happens if you don't await a task?

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.


1 Answers

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); 
like image 96
Stephen Cleary Avatar answered Oct 06 '22 01:10

Stephen Cleary