gpt4 book ai didi

c# - 对 ConcurrentDictionary 的线程安全更改

转载 作者:行者123 更新时间:2023-12-02 18:20:17 28 4
gpt4 key购买 nike

我正在 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是线程安全的。

最佳答案

我想你想要GetOrAdd ,它被明确设计为获取现有项目,或者在给定键没有条目的情况下添加新项目。

var collection = result.GetOrAdd(someKey, _ => new ItemCollection());
collection.Add(newItem);

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

关于c# - 对 ConcurrentDictionary 的线程安全更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24185431/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com