Search code examples
c#asynchronousparallel.foreach

Why Iterations with lower index is not performed?


The code successfully build no compilation error however nothing iteration on runtime. I Stopped the loop iteration at 200 so loop will not proceed further but loop does not execute iteration lower than < 200.

I am not sure. Is there anything alternative of Stop I can use to fix this code? Why Iterations with lower index is not performed?

How to fix this issue. I googled stuff but all vain. Please consider the following code.

 static void Main(string[] args)
    {
        var values= Enumerable.Range(0, 500).ToArray();
        ParallelLoopResult result = Parallel.For(0, values.Count(),
            (int i, ParallelLoopState loopState) => {
                if (i == 200)
                    loopState.Stop();
                WorkOnItem(values[i]);
            });

        Console.WriteLine(result);

    }
static void WorkOnItem(object value) {
        System.Console.WriteLine("Started working on: " + value);
        Thread.Sleep(100);
        System.Console.WriteLine("Finished working on: " + value); }

Any help to solve this issue would be appreciated. Thanks


Solution

  • You should call loopState.Break() instead of loopState.Stop().

    From the documentation of ParallelLoopState.Break method:

    Break indicates that no iterations after the current iteration should be run. It effectively cancels any additional iterations of the loop. However, it does not stop any iterations that have already begun execution. For example, if Break is called from the 100th iteration of a parallel loop iterating from 0 to 1,000, all iterations less than 100 should still be run, but the iterations from 101 through to 1000 that have not yet started are not executed.