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

Álv*_*cía 0 c# task-parallel-library parallel.foreach

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

我有类似的东西:

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

我想避免属性iterator.Position中的间隙,也避免重复.

我已经看到了一个例子来处理部分结果的总和,例如在本文档中,但它并不是我需要的相同情况.

因此,我想知道是否有任何更新计数器以避免在并行foreach内部更新时出现间隙和重复.

谢谢.

M.k*_*ary 5

具有3个参数的lambda参数的并行foreach的重载已经有计数器.

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

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

请注意,counter是long类型,因此如果Position是int类型,则必须将其强制转换为int