【问题标题】:Parallel.For combined with ConcurrentBag seems not to be thread-safeParallel.For 与 ConcurrentBag 结合似乎不是线程安全的
【发布时间】:2021-06-10 08:39:34
【问题描述】:

我第一次使用 Parallel.For 来填充列表(这里是 ConcurrentBag) 但似乎 ConcurrentBag 从其他线程接收数据。 我在 xSource 中有大量数据,任务是将其分发到多个列表。 这里有什么问题?

public static void getNearXvalues(double deltaX, double xCenter, double[] xSource, out double[] xNear)
{
    var xList = new ConcurrentBag<double>();

    Parallel.For(0, xSource.Length, i =>
    {
        if((Mat.Abs(xCenter-xSource)<deltaX)
        {
            xList.Add(xSource[i]);
        }
    });
    xNear = xList.ToArray();
}

【问题讨论】:

    标签: thread-safety parallel.for


    【解决方案1】:

    我也遇到了同样的问题,没来得及调查,我用 Semaphore 解决了这个问题。 https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphore?view=net-5.0

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 2019-01-05
      • 2015-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多