Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net - How does parallel.for works

How does parallel.for works. Does it invoke threads for each loop/ divide the loops in parts and execute them in parallel? If it does then can we ensure the same result as normal for loop? I tested for performance and it really uses multi core processors. But i want to know the internal working as to how this works

like image 585
Ankit Avatar asked Mar 29 '11 06:03

Ankit


People also ask

What is parallel processing in C#?

Parallel programming is a programming model wherein the execution flow of the application is broken up into pieces that will be done at the same time (concurrently) by multiple cores, processors, or computers for the sake of better performance.

How do parallel for loops differ from standard for loops?

What is the difference between the Parallel For loop and Standard C# for loop? In the case of the standard C# for loop, the loop is going to run using a single thread whereas, in the case of the Parallel For loop, the loop is going to execute using multiple threads.

What is parallel for?

: lying or moving in the same direction but always the same distance apart parallel lines Train tracks are parallel. parallel. noun. Kids Definition of parallel (Entry 2 of 3) 1 : a line or surface that lies at or moves in the same direction as another but is always the same distance from it.


2 Answers

Parallel.For partitions the work for a number of concurrent iterations. Per default it uses the default task scheduler to schedule the iterations, which essentially uses the current thread as well as a number of thread pool threads. There are overloads that will allow you to change this behavior.

A parallel loop may look very similar to a regular loop, but there are actually a number of important differences. First of all the order of the iterations is not guaranteed. I.e. the code cannot assume any specific order. Doing so will lead to unpredictable results.

Also, since the code may be run on multiple threads exception handling is completely different from a regular for loop. Parallel.For will catch exceptions for the threads and marshal these back to the calling thread as inner exceptions in an instance of AggregateException.

For additional details please check Parallel Programming with Microsoft .NET by Microsoft patterns and practices.

like image 135
Brian Rasmussen Avatar answered Nov 03 '22 00:11

Brian Rasmussen


parallel.for loops run iterations of the loop in different processes in parallel. You can only use this if iterations are independent of one another. Only if the iterations are independent, you can assume the same results will be produced by a parallel and non-parallel for loop.

like image 45
Elad Lachmi Avatar answered Nov 03 '22 01:11

Elad Lachmi