Home > DeveloperSection > Forums > How Parallel.ForEach works internally?
Anupam Mishra

Total Post:135

Posted on    January-13-2016 11:01 PM

 C# C#  .NET  Threading 

 1 Reply(s)
 701  View(s)
Rate this:
i just like to know how Parallel.ForEach()  works?
does it start multiple thread or it is not at all related with thread?
thank you.

Manoj Bhatt
Manoj Bhatt

Total Post:154

Posted on    January-14-2016 6:57 AM

The Parallel class’s ForEach method is a multi-threaded implementation of a common loop construct in C#, the foreach loop. Recall that a foreach loop allows you to iterate over an enumerable data set represented using an IEnumerable

Parallel.ForEach is similar to a foreach loop in that it iterates over an enumerable data set, but unlike foreach, Parallel.ForEach uses multiple threads to evaluate different invocations of the loop body. As it turns out, these characteristics make Parallel.ForEach a broadly useful mechanism for data-parallel programming. In order to evaluate a function over a sequence in parallel, an important thing to consider is how to break the iteration space into smaller pieces that can be processed in parallel. This partitioning allows each thread to evaluate the loop body over one partition. 

Parallel.ForEach has numerous overloads.The IEnumerable source specifies the sequence to iterate over, and the Action body specifies the delegate to invoke for each element. For the sake of simplicity, we won’t explain the details of the other signatures of Parallel.ForEach; the list of different overloads can be found here.

Don't want to miss updates? Please click the below button!

Follow MindStick