问题描述
我第一次使用 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