Parallel.For 与 ConcurrentBag 结合似乎不是线程安全的

问题描述

我第一次使用 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();
}

解决方法

我遇到了同样的问题,没有时间调查,我用信号量解决了这个问题。 https://docs.microsoft.com/en-us/dotnet/api/system.threading.semaphore?view=net-5.0

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...