Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Parallel.ForEach obsolete. old, out of fashion?

Good day,

Parallel execution can be achieved through multiple ways. From strictly manual "multithreading" to using various "helpers" created by Microsoft. One of those helpers is the Parallel class.

One of my colleagues is insisting that Parallel.ForEach (or Parallel class overall) is "old" and shouldn't be used. Instead, he says, one should use async operations. In other words you should use Task.WhenAll() instead of Parallel.ForEach() .

When asked why not use Parallel.ForEach(), when this is exactly what was needed - multiple expensive operations executed in parallel, he replied that Parallel.ForEach() is old and that Microsoft recommends using async/await wherever possible.

I searched all over MSDN and Stackoverflow and everywhere I could but I couldn't find anything pointing at the necessity of using async/await instead of .Parallel. While you often can achieve similar results by interchanging these tools it doesn't mean that Parallel.ForEach is obsolete. Or does it?

Anyone has a link to some "best practices" or "recommendations" by a reputable body (MSDN?) that would say that Parallel.ForEach() is being phased out and one needs to stick with creating, running and awaiting tasks?

Please do not post answers related to Parallel VS Async for this as this is not the question.

The question is: Since you can make tasks run in parallel using async/await WhenAll (WaitAll etc.), does it make 'Parallel' class obsolete, old, or not fashionable in .NET 4.5 onward?

like image 829
agfc Avatar asked Apr 28 '15 12:04

agfc


1 Answers

I don't think Parallel.ForEach is obsolete.

Ever since introducing the Task Parallel Library (TPL) with .NET 4, Microsoft has distinguished between "Data Parallelism" (e.g. Parallel.ForEach) and "Task Parallelism" (Task). From MSDN:

  • "Data parallelism refers to scenarios in which the same operation is performed concurrently (that is, in parallel) on elements in a source collection or array."
  • "[T]ask parallelism refers to one or more independent tasks running concurrently."

(Emphasis by me. Like dcastro commented (above): "Your friend is confusing parallelism with asynchrony.")

These two types of parallelism/concurrency pursue different goals, so the TPL offers different capabilities for each of them.

Conceptually, Task.WhenAll belongs into the task parallelism category, so I don't think it obsolesces something that belongs to the other (data parallelism) category.

like image 85
stakx - no longer contributing Avatar answered Sep 22 '22 12:09

stakx - no longer contributing