1

我有一种情况是并行处理这组数据,最后我想知道总共有多少个数据处理成功了。我按照http://msdn.microsoft.com/en-us/library/dd460703.aspxhttp://reedcopsey.com/2010/01/22/parallelism-in-net上的示例提供了以下虚拟代码-part-4-imperative-data-parallelism-aggregation/

    public void DoWork2()
    {
        int sum = 0;
        Parallel.For<int>(0, 10,
            () => 0,
            (i, lockState, localState) =>
            {
                DummyEntity entity = DoWork3(i);
                if (entity != null)
                {
                    Console.WriteLine("Processed {0}, sum need to be increased by 1.", i);
                    return 1;
                }
                else
                {
                    Console.WriteLine("Processed {0}, sum need to be increased by 0.", i);
                    return 0;
                }
            },
            localState =>
            {
                lock (syncRoot)
                {
                    Console.WriteLine("Increase sum {0} by {1}", sum, localState);
                    sum += localState;
                }
            }
            );
        Console.WriteLine("Total items {0}", sum);
    }

    private DummyEntity DoWork3(int i)
    {
        if (i % 2 == 0)
        {
            return new DummyEntity();
        }
        else
        {
            return null;
        }
    }

但是,每次我运行时结果都会发生变化。我认为代码有问题。但无法弄清楚为什么。

4

1 回答 1

2

您的问题是您在重载中的选择。您已经存储了本地状态信息以最大限度地减少全局状态的使用,但您没有使用本地状态。

localState如果您从给出的示例中注意到他们在循环主体中使用小计(您所称的):

subtotal += nums[j];
return subtotal;

将此与您的代码进行比较(更简洁一些):

if (entity != null)
{
    return 1;
}
else
{
    return 0;
}

没有提及localState,因此您实际上已经丢弃了一些答案。如果您将其更改为阅读:

if (entity != null)
{
    return localState + 1;
}
else
{
    return localState;
}

您将在命令行上找到以下答案(对于这个给定的问题):

Total items 5

使用本地状态是为了减少对共享状态的访问。

这是使用 0..50 作为范围的片段:

Processed 22, sum need to be increased by 1.
Processed 23, sum need to be increased by 0.
Increase sum 0 by 1
Processed 8, sum need to be increased by 1.
Processed 9, sum need to be increased by 0.
Processed 10, sum need to be increased by 1.
Processed 11, sum need to be increased by 0.
Increase sum 1 by 2
Increase sum 3 by 8
Increase sum 11 by 10
Processed 16, sum need to be increased by 1.
Processed 17, sum need to be increased by 0.
Processed 18, sum need to be increased by 1.
Increase sum 21 by 4
Total items 25
于 2013-01-16T17:56:22.473 回答