在多线程中,字典是否可能返回错误的值 C#



我在多线程环境中有一个 c# 字典。我正在使用 TryGetValue 进行无锁阅读,同时字典正在重组。是否可以获得与此键无关的完全不同的值?我的意思不仅仅是一个不是最新的值,而是一个与不同键对应的完全错误的值。

public static bool ChangeKey<TKey, TValue>(this IDictionary<TKey, TValue> dict,
                                       TKey oldKey, TKey newKey)
    {
        TValue value;
        if (!dict.TryGetValue(oldKey, out value))
            return false;
        dict.Remove(oldKey);  // do not change order
        dict[newKey] = value;  // or dict.Add(newKey, value) depending on ur comfort
        return true;
    }

不,不可能获得不同的值表单字典。如果 TryGetValue 返回 true,则该值应该是正确的。

为什么不使用ConcurrentDictionar?ConcurrentDictionary 是一个线程安全的字典实现

如上所述使用了 ConcurrentDictionary...这解决了我的问题..

最新更新