我有一种情况是并行处理这组数据,最后我想知道总共有多少个数据处理成功了。我按照http://msdn.microsoft.com/en-us/library/dd460703.aspx和http://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;
}
}
但是,每次我运行时结果都会发生变化。我认为代码有问题。但无法弄清楚为什么。