3

What is the difference between:

foreach(Task task in someTasks)
{
    task.Wait();
}

and

Task.WaitAll(sometasks);

In essence, looking from the end result perspective, they should be doing the same thing?

svick
  • 236,525
  • 50
  • 385
  • 514
Denis Biondic
  • 7,943
  • 5
  • 48
  • 79
  • Yesterday I asked a similar question but which wasn't actually what I was looking for, because I asked it completely in a wrong way... https://stackoverflow.com/questions/22174915/task-parallel-library-difference-between-parallel-foreach-task-wait-and-tas?rq=1 – Denis Biondic Mar 05 '14 at 07:35
  • 1
    I think there could be a difference when one of the tasks get cancelled or throws an exception. – Dirk Mar 05 '14 at 07:40
  • 1
    hmmm perhaps that is a good point, maybe WaitAll with throw an AggregateException containing exceptions from all the Wait() calls? – Denis Biondic Mar 05 '14 at 07:41

1 Answers1

5

The difference is in the exception handling. If task.Wait(); throws, the foreach loop is exited. WaitAll will catch all exceptions and throw an AggregateException containing them.

See also: Task.WaitAll and Exceptions

Community
  • 1
  • 1
Henrik
  • 23,186
  • 6
  • 42
  • 92