为什么不执行具有较低索引的迭代?

Why Iterations with lower index is not performed?

代码成功构建,没有编译错误,但在运行时没有迭代。我 Stopped loop iteration 在 200 所以循环将不会继续进行但循环不会执行低于 < 200 的迭代。

我不确定。 我可以使用 Stop 的替代方法来修复此代码吗? 为什么不执行具有较低索引的迭代?

如何解决这个问题。我用谷歌搜索了一些东西,但都是徒劳的。 请考虑以下代码。

 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); }

如能帮助解决此问题,我们将不胜感激。谢谢

您应该调用 loopState.Break() 而不是 loopState.Stop()

来自ParallelLoopState.Break方法的文档:

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.