我很难用并行方法获得完美的结果。
我所做的
protected void Page_Load(object sender, EventArgs e)
{
List<int> listInt = new List<int>();
for (int i = 0; i < 10000; i++)
{
listInt.Add(i);
}
int cnt = 0;
Parallel.ForEach(listInt, num =>
{
cnt++;
}
);
System.Threading.Thread.Sleep(0);
//it should show 10000 but it gives random result
Response.Write(cnt);
}我本来希望得到10000作为回应,但它是随机的结果。
我做错了什么才能得到准确的结果。
现场测试到了。
非常感谢。
发布于 2013-12-20 13:58:58
您的代码不是线程安全。
你可以使用这样的东西:
private static readonly object SyncRoot = new object();和
lock (SyncRoot)
{
cnt++;
}检查一下这个点小提琴http://dotnetfiddle.net/D7QoP9
发布于 2013-12-20 13:54:55
您的代码不是“线程安全”,而是“种族”。
在cnt++周围添加一个锁以查看预期的结果。
或者直接用
Interlocked.Increment(ref cnt);https://stackoverflow.com/questions/20705105
复制相似问题