对 ConcurrentDictionary 的线程安全更改

Dav*_*New 2 c# parallel-processing task-parallel-library concurrentdictionary parallel.foreach

ConcurrentDictionary我正在循环中填充 a Parallel.ForEach

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

如何在不使用 lock 语句的情况下以线程安全的方式执行最后的步骤?

编辑: 假设这ItemCollection是线程安全的。

Jon*_*eet 5

我认为您想要GetOrAdd,它被明确设计为获取现有项目,或者如果给定键没有条目则添加新项目。

var collection = result.GetOrAdd(someKey, _ => new ItemCollection());
collection.Add(newItem);
Run Code Online (Sandbox Code Playgroud)

正如问题评论中所指出的,这假设ItemCollection是线程安全的。