Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET 4 ... Parallel.ForEach() question

I understand that the new TPL (Task Parallel Library) has implemented the Parallel.ForEach such that it works with "expressed parallelism." This means it does not guarantee that your delegates will run in multiple threads, but rather it checks to see if the host platform has multiple cores, and if true, only then does it distribute the work across the cores (essentially 1 thread per core).

If the host system does not have multiple cores (getting harder and harder to find such a computer) then it will run your code sequentially like a "regular" for each loop would. Pretty cool stuff, frankly.

Normally I would do something like the following to place my long-running operation on a background thread from the ThreadPool:

ThreadPool.QueueUserWorkItem(new WaitCallback(targetMethod), new Object2PassIn() );

In a situation whereby the host computer only has a single core does the TPL's Parallel.ForEach automatically places the invocation on a background thread? Or, should I manually invoke any TPL calls from a background thread so that if I am executing from a single core computer at least that logic will be off of the GUI's dispatching thread?

My concern is if I leave the TPL in charge of all this I want to ensure if it determines it's a single core box that it still marshals the code that's inside of the Parallel.ForEach loop onto a background thread like I would have done, to not block my GUI.

like image 989
BonanzaDriver Avatar asked Jan 05 '11 02:01

BonanzaDriver


2 Answers

Your assumptions are incorrect.
Parallel.For is, always, a blocking call.

Even if the computer has multiple cores, it will still wait for all of the threads to finish before returning.

If you don't want to freeze the UI, you will always need to explicitly call the ThreadPool.

like image 174
SLaks Avatar answered Nov 17 '22 11:11

SLaks


Through my experience with Parallel.ForEach and Parallel.For loops, I have noticed that the order can be out of order, something you might want to consider before you implement.

Such as a basic for loop will produce:

Product 1 Product 2 Product 3 Product 4

And the Parallel loop can produce, but not always:

Product 3 Product 1 Product 2 Product 4

Just keep that in mind lads.

like image 34
TGarrett Avatar answered Nov 17 '22 13:11

TGarrett