【发布时间】:2023-04-04 01:30:01
【问题描述】:
我必须从 Parallel.ForEach 中删除 lock 对象。我应该使用ConcurrentBag 还是直接删除它?如果没有 lock 对象,它是线程安全的吗?
results 是 List<>。
Parallel.ForEach(entityList, options,
() =>
{
List<Customer> childrenResult = new List<Customer>();
return childrenResult;
},
(childrenObject, loopState, childrenResult) =>
{
childrenResult.AddRange(currentChildrenManager.Prepare(childrenObject, currentAnalyticalDataHolder, () => loopState.IsStopped, out childrenAllData));
return childrenResult;
},
(childrenResult) =>
{
lock (lockingObject)
{
if (childrenResult == null)
results.AddRange(new List<Customer>());
else if (currentChildrenManager.RowOrFilteredRowLimitation == null)
results.AddRange(childrenResult);
else
{
int leftCount = currentChildrenManager.RowOrFilteredRowLimitation.GetRelativRowLimitation(provider.IsForGenerationTime) - results.Count();
if (leftCount > 0)
{
if (childrenResult.Count() > leftCount)
{
tAllData = currentChildrenManager.OnlyFirst;
results.AddRange(childrenResult.Take(leftCount));
}
else
results.AddRange(childrenResult);
}
else
{
tAllData = currentChildrenManager.OnlyFirst;
}
}
}
});
【问题讨论】:
标签: c# multithreading parallel-processing thread-safety parallel.foreach