使用Parallel获得完美结果时遇到问题。
我做了什么
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作为回应,但它会给出随机结果。
我做错了什么来获得准确的结果。
非常感谢你。
答案 0 :(得分:4)
您的代码不是“线程安全”,即“种族”。
在cnt++
周围添加锁定以查看预期结果。
或者只是使用
Interlocked.Increment(ref cnt);
答案 1 :(得分:4)
您的代码不是线程安全的。
您可以使用以下内容:
private static readonly object SyncRoot = new object();
和
lock (SyncRoot)
{
cnt++;
}
检查此dotnetfiddle http://dotnetfiddle.net/D7QoP9