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

Posted by CirrusFlyer on Stack Overflow See other posts from Stack Overflow or by CirrusFlyer
Published on 2011-01-05T02:11:26Z Indexed on 2011/01/05 2:53 UTC
Read the original article Hit count: 159

Filed under:
|
|

I understand that the new TPL (Task Parallel Library) has implemented the Parallel.ForEach() such that it works with "expressed parallelism." Meaning, 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 sequenceally like a "regular" foreach 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 place the invocation on a background thread? Or, should I manaully invoke any TPL calls from a background thead 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 marshalls the code that's inside of the Parallel.ForEach() loop on to a background thread like I would have done, so as to not block my GUI.

Thanks for any thoughts or advice you may have ...

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET