gpt4 book ai didi

c# - 使用 foo[bar] = baz 添加到 ConcurrentDictionary 是线程安全的吗?

转载 作者:行者123 更新时间:2023-11-30 21:26:55 25 4
gpt4 key购买 nike

我不喜欢附加到 ConcurrentDictionary 的方法。 AddOrUpdate 需要一个 func,而 GetOrAdd 在您只是寻找键以获取值时添加。所以我想像普通字典一样使用它(为了安全起见,我使用 ContainsKey)

docs说“无条件地在字典中存储键/值对,并覆盖已经存在的键的值”,使用索引器的 setter :dictionary[key] = newValue

但是这个操作仍然是线程安全的吗?底部的评论说“ConcurrentDictionary 的所有公共(public)和 protected 成员都是线程安全的,可以从多个线程并发使用。”但我不能 100% 确定他们认为上面的 setter 包含在这里。

最佳答案

您可以在引用源 -- https://referencesource.microsoft.com/#mscorlib/system/Collections/Concurrent/ConcurrentDictionary.cs 查看 ConcurrentDictionaryindexer 实现

    public TValue this[TKey key]
{
get
{
TValue value;
if (!TryGetValue(key, out value))
{
throw new KeyNotFoundException();
}
return value;
}
set
{
if (key == null) throw new ArgumentNullException("key");
TValue dummy;
TryAddInternal(key, value, true, true, out dummy);
}
}

如果您注意到 setter 调用 TryAddInternal,这是线程安全的实现

enter image description here

关于c# - 使用 foo[bar] = baz 添加到 ConcurrentDictionary 是线程安全的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58649814/

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