Search code examples
c#.netparallel-processingtask-parallel-libraryparallel.foreach

Parallel.ForEach - Where is it running on single core machines?


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.


Solution

  • 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.