public static ParallelLoopResult For<TLocal>(int fromInclusive, int toExclusive, Func<TLocal> localInit, Func<int, ParallelLoopState, TLocal, TLocal> body, Action<TLocal> localFinally); 

I have a few small questions regarding the above overload, namely:

  1. Task is created for each iteration of the for loop?
  2. The destination in the body of the first int input parameter.
  • Pay attention to update the answer! The initial answer was incorrect. - VladD

1 answer 1

1) The question assumes the existence of a specific, documented mechanism for implementing multithreading in this function. How exactly parallelization is achieved is an internal implementation detail.

In the current implementation , a special type of root Task is created ( ParallelForReplicatingTask ), which is able to create its own lightweight copies . But these classes are internal, and inaccessible to the programmer. And of course in the next version, the implementation has the right to change without warning.

2) From the documentation :

The body range is invoked (from Incclusive , to Exclusive ). It can be used prematurely, it can be used for the following parameters.

That is, the first parameter is the total number of iterations. It can be used, for example, in order to understand how much of the overall work is done.


An important update : as correctly noted by @Grundy, the meaning of the first parameter in the body is the current iteration number, not the number of iterations. Apparently, the documentation error. Note that the numbers may well not be delivered in a row. For example, such a cycle:

 Parallel.For<string>( 0, 20, () => "Thread #" + Thread.CurrentThread.ManagedThreadId, (iter, loopState, localState) => { var res = localState + " " + iter; Console.WriteLine(res); return localState; }, s => { }); 

I issued:

 Thread #10 0 Thread #10 1 Thread #10 3 Thread #10 4 Thread #10 5 Thread #10 6 Thread #10 7 Thread #10 8 Thread #10 9 Thread #10 10 Thread #10 11 Thread #10 12 Thread #10 13 Thread #6 2 Thread #6 16 Thread #6 17 Thread #6 18 Thread #6 19 Thread #10 15 Thread #11 14 
  • the iteration count - is this the total number of iterations , not the current iteration number? - Grundy
  • Google : - \ - VladD
  • @Grundy: But I will double-check, because the iteration number is important, of course. - VladD
  • one
    Still, I'm right: the current iteration number is passed to the body - Grundy
  • @Grundy: And the truth is, I'll fix it now. Thank! - VladD