【发布时间】:2014-06-12 13:17:00
【问题描述】:
我在Parallel.ForEach 循环中填充ConcurrentDictionary:
var result = new ConcurrentDictionary<int, ItemCollection>();
Parallel.ForEach(allRoutes, route =>
{
// Some heavy operations
lock(result)
{
if (!result.ContainsKey(someKey))
{
result[someKey] = new ItemCollection();
}
result[someKey].Add(newItem);
}
}
如何在不使用 lock 语句的情况下以线程安全的方式执行最后一步?
编辑:假设ItemCollection 是线程安全的。
【问题讨论】:
-
ItemCollection.Add线程安全吗?如果没有,你需要一把锁。 -
@ken2k:除了我的情况有条件因素。如果该键不存在,则创建一个新的
ItemCollection,否则在该键的现有ItemCollection中添加一个项目。 -
@dcastro:是的,请假设 ItemCollection 是线程安全的。
标签: c# parallel-processing task-parallel-library parallel.foreach concurrentdictionary