Stop vs Break in Parallel.For

.net, c#, loops, task-parallel-library

Solution

`loopState.Break()` does not break the function like a `return`. So the line after the `loopState.Break()` will still be executed. After that scope has ended for that number, `for` checks if the `loopState.Break()` had been called. If so, all loops are allowed to continue until the number has been reached that called `Break`.

In your example, the loops with 0 till 24 will break at the same time as the loop 25 till 49 (and display their "breaking" numbers).

Loop 50..74 and 75..99 will not even get started because the second loop 25..49 has already aborted the whole for-operation, since their staring numbers are greater then the breaking number 10.

Problem

I have difficulty to understand `loopState.Stop()` and `loopState.Break()`. I have read MSDN and several posts about it but I am still confused. What I understand is that every iteration partitioner gives remaining indexes for threads to process and `loopState.Stop()` stops all threads and `loopState.Break()` stops the current thread. However lets consider the following situation: ``` Parallel.For(0, 100, (i, loopState) => { if (i >= 10) loopState.Break(); Debug.Write(i); }); ``` For this loop I have following result: ``` 0 25 1 2 3 4 5 6 7 8 9 10 ``` I have no idea why in the result there is 10 and 25 numbers. Anyone can help? P.S. I have i5 520M CPU (2 cores => 4 Threads)

Original source

Related problems