Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

What is the difference between:

Parallel.ForEach(sometasks, x => x.Wait());

and

Task.WaitAll(sometasks);

EDIT:

Well I am not fully sure why I included Parallel into the question :/ ... What I had in mind was:

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

but I just included Parallel.ForEach thinking it is the same thing, while of course its not --- it spawns a thread for each task to wait, which is big overhead.

share|improve this question
1  
Parallel.ForEach(sometasks, x => x.Wait()); Doesn't makes sense for me –  Sriram Sakthivel Mar 4 at 14:41

3 Answers 3

up vote 3 down vote accepted

Though Parallel.ForEach(sometasks, x => x.Wait()); makes no sense for me.

Short answer is

Parallel.ForEach: With your code, blocks at least two threads. Calling thread and ThreadPool thread(s) as well.

Task.WaitAll: Blocks only the calling thread.

share|improve this answer

Parallel class is designed to provide simple and efficient data-paralellism ( you distribute the SAME task on different data and then collect the result). Typical examples of these problems are vector or matrix processing problems (matrix multiplication, image processing etc).

Tasks are designed for task-based parallelism - to help you structure a complicated asynchronious execution with possibility to handle task dependencies, failures etc.

share|improve this answer

The big difference between WaitAll() and calling Wait() in a loop is when one or more Tasks fail:

  • WaitAll() will always wait for all the Tasks to complete, even if some of them fail. If more than one Task fails, it will throw an AggregateException that contains exceptions from all the failed Tasks.
  • Wait() in a loop will throw as soon as it encounters the first exception. That means it may not wait for all the Tasks to complete and you're also going to learn only about one exception, even if there is more than one.
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.