【问题标题】:System.Threading.Tasks.Parallel [duplicate]System.Threading.Tasks.Parallel [重复]
【发布时间】:2013-12-20 13:50:54
【问题描述】:

我无法使用 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 作为响应,但它给出的是随机结果。

为了得到准确的结果,我做错了什么。

Live test is here.

非常感谢。

【问题讨论】:

标签: c# asp.net multithreading parallel.foreach


【解决方案1】:

您的代码不是线程安全的。

你可以这样使用:

private static readonly object SyncRoot = new object();

lock (SyncRoot)
{
    cnt++;
}

检查这个 dotnetfiddle http://dotnetfiddle.net/D7QoP9

【讨论】:

  • 把相关的代码位放在你的帖子中,这样如果将来小提琴消失了。
  • @arpad,非常感谢。
【解决方案2】:

您的代码不是“线程安全的”,而是“竞赛”。

cnt++ 周围添加一个锁以查看预期结果。

或者直接使用

Interlocked.Increment(ref cnt);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-06
    • 1970-01-01
    • 1970-01-01
    • 2020-04-17
    • 1970-01-01
    • 2012-06-22
    • 2016-07-08
    相关资源
    最近更新 更多