当公共变量在并行foreach中递增时如何获取下一个值?

How to get next value when a common variable is increment in a parallel foreach?

我有一个在 foreach 中更新的公共变量,它是一个计数器,所以我想在并行 foreach 中分配下一个计数器。

我有类似的东西:

int myCommonCounter = 5;
Parallel.Foreach(myList, (iterator, state) =>
{
    if(iterator.MyProperty == X)
    {
        iterator.Position = miCommonCounter;
        miCommonCounter = miCommonCunter + 1;
    }
});

我想避免 属性 iterator.Position 中的空白,并避免重复。

我看过一个对部分结果求和的示例,for example in this documentation,但它并不是我需要的那种情况。

所以我想知道当我在并行 foreach 中更新时,是否有任何方法可以更新计数器以避免间隙和重复。

谢谢。

The overload of Parallel foreach that has 3 parameters for lambda argument has counter already.

您应该使用它而不是编写手动计数器。它没有重复项。它也不会有间隙,除非你出于某种原因停止循环。

Parallel.ForEach(source.Where(x => /*condition*/), (x, state, counter) =>
{
     iterator.Position = (int) counter;
});

注意 counter 是 long 类型,所以如果 Position 是 int 类型,你必须将它转换为 int