【问题标题】:is it possible in multithreading that dictionary return wrong values c#在多线程中字典是否有可能返回错误的值c#
【发布时间】:2019-05-28 15:13:20
【问题描述】:

我在多线程环境中有一个 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;
    }

【问题讨论】:

  • 您使用的是什么实现方式?如果是System.Collections.Generic.Dictionary&lt;TKey, TValue&gt;,那么不,你不能在没有锁定的情况下在线程之间安全地使用它。
  • 谢谢老哥,问题解决了...你能告诉我如何关闭或删除这个帖子吗??
  • 您无法关闭问题,但您可以接受答案或删除问题。

标签: multithreading c#-4.0 .net-4.0


【解决方案1】:

不,不可能得到不同的值形式的字典。如果 TryGetValue 返回 true,那么该值应该是正确的。

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-17
      • 2021-06-13
      • 2014-06-02
      • 1970-01-01
      • 2019-05-22
      • 1970-01-01
      • 2020-09-17
      • 1970-01-01
      相关资源
      最近更新 更多