【问题标题】:Different behaviour when collection modified between Dictionary and ConcurrentDictionary在 Dictionary 和 ConcurrentDictionary 之间修改集合时的不同行为
【发布时间】:2015-02-12 14:33:39
【问题描述】:

使用下面列表中的普通字典代码,我得到异常

集合已修改;枚举操作可能无法执行。

Dictionary<int, int> dict2 = new Dictionary<int, int>();
dict2.Add(1, 10);
dict2.Add(2, 20);
dict2.Add(3, 30);
dict2.Add(4, 40);

foreach (var d in dict2)
{
    if (dict2.ContainsKey(2))
        dict2.Remove(2);

    if (dict2.ContainsKey(3))
        dict2.Remove(3);
}

但是使用 ConcurrentDictionary,这可以正常工作。

ConcurrentDictionary<int, int> dict1 = new ConcurrentDictionary<int, int>();
dict1.AddOrUpdate(1, 10, (k,v)=> 10);
dict1.AddOrUpdate(2, 20, (k, v) => 20);
dict1.AddOrUpdate(3, 30, (k,v)=> 30);
dict1.AddOrUpdate(4, 40, (k,v)=> 40);

foreach (var d in dict1)
{
    int x;
    if (dict1.ContainsKey(2))
        dict1.TryRemove(2, out x);

    if (dict1.ContainsKey(3))
        dict1.TryRemove(3, out x);
}

为什么会有不同的行为?

【问题讨论】:

  • 因为它们是不同的类,所以它们的行为不同。 ConcurrentDictionary 旨在与多个线程一起使用,其中一个可以删除项目,而另一个正在迭代它,因此它不会引发异常。
  • 我知道这些是不同的类,但我认为只读枚举的概念适用于所有集合类。
  • 不,不是所有的类在修改为枚举时都会抛出异常。 System.Collections.Concurrent 命名空间中的类是例外。我记得 winforms 中的 ControlCollection 也不会引发此异常。

标签: c# dictionary .net-4.0 enumeration concurrentdictionary


【解决方案1】:

原因是 Dictionary 和 ConcurrentDictionary 有不同的用途。 ConcurrentDictionary - 应该处理并发问题(从不同线程编辑),而 Dictionary 会给你更好的性能。

不同行为的原因是:GetEnumerator() 方法的不同实现。

现在我将解释 Dictionary 出现异常的原因以及 ConcurrentDictionary 没有出现异常的原因。

foreach 语句是类似以下内容的语法糖:

    var f = dict.GetEnumerator();

        while (f.MoveNext())
        {
            var x = f.Current;

            // your logic
        }

Dictionary 中的“GetEnumerator()”返回名为“Enumerator”的新结构实例

这个结构实现了:IEnumerator >KeyValuePair>TKey,TValue>>,IDictionaryEnumerator和他的C'tor看起来像:

        internal Enumerator(Dictionary<TKey,TValue> dictionary, int getEnumeratorRetType) {
            this.dictionary = dictionary;
            version = dictionary.version;
            index = 0;
            this.getEnumeratorRetType = getEnumeratorRetType;
            current = new KeyValuePair<TKey, TValue>();
        }

“枚举器”中 MoveNext() 的实现首先验证源字典没有被修改:

      bool moveNext(){
            if (version != dictionary.version) {
                throw new InvalidOperationException....
            }
            //the itarate over...
      }

ConcurrentDictionary 中的“GetEnumerator()”实现方式不同:

   IEnumerator<KeyValuePair<TKey, TValue>> GetEnumerator(){
         Node[] buckets = m_tables.m_buckets;

         for (int i = 0; i < buckets.Length; i++)
         {

             Node current = Volatile.Read<Node>(ref buckets[i]);

             while (current != null)
             {
                 yield return new KeyValuePair<TKey, TValue>(current.m_key,  current.m_value);
                 current = current.m_next;
             }
         }
    }

在此实现中,有一种称为“惰性求值”的技术,return 语句将返回值。 当消费者调用 MoveNext() 时,您将返回“current = current.m_next;” 因此,GetEnumerator() 内部没有“不改变”验证。

如果您想避免“字典编辑”出现异常,则: 1.迭代到要删除的元素 2.删除元素 3. 在调用 MoveNext() 之前中断

在你的例子中:

        foreach (var d in dict2)
        {
            if (dict2.ContainsKey(1))
                dict2.Remove(1);

            if (dict2.ContainsKey(3))
                dict2.Remove(3);

            break; // will prevent from exception
        }

有关 ConcurrentDictionary 的 GetEnumerator() 的更多信息: https://msdn.microsoft.com/en-us/library/dd287131(v=vs.110).aspx

【讨论】:

    【解决方案2】:

    ConcurrentDictionary 的目的是允许多个线程以最少的锁定来使用它。如果一个线程希望从一个典型的并发数据结构中接收一个枚举,该枚举代表了在某个时刻持有的数据的精确组合,则有必要使用一个锁来确保在创建快照时不会发生更新。结构已建成。即使在使用ConcurrentDictionary 时,想要构造这样一个快照的代码也可以使用这样的方法。

    然而,在许多情况下,代码会对满足以下所有条件的任何枚举感到满意:

    • 枚举将包括枚举之前存在的所有数据项,在整个枚举过程中继续存在,无需修改。

    • 枚举将不包括在枚举期间的任何时间集合不包含的任何数据项。

    • 如果在枚举开始时集合不包含某项,但在枚举过程中添加和/或修改该项N次,则枚举上报该项不超过N次。

    • 如果集合在枚举开始时包含一个item,并且在枚举过程中添加和/或修改了N次,则枚举上报该item不超过N+1次。

    满足上述标准的枚举方法的成本可能比需要返回“快照”的方法便宜;因为这样的枚举通常很有用,ConcurrentDictionary 定义了它的GetEnumerator 方法来返回更便宜的那个。如果有这种倾向,这种行为不会阻止代码使用外部锁定,但如果唯一可用的枚举器总是拍摄快照,那么在不需要精确快照时,代码将无法使用更高性能的枚举。

    PS--我碰巧认为 ConcurrentDictionary 包含一些明确请求其内容的可枚举快照的方法会很有帮助,即使拍摄这样的快照会相对较慢并且会阻塞一些或所有并发访问。即使大型集合的快照太慢而无法频繁使用,拥有一个真正的集合快照在许多调试场景中也很有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-20
      • 2015-09-07
      • 1970-01-01
      • 2022-01-23
      • 2011-05-18
      • 1970-01-01
      相关资源
      最近更新 更多