我可以从该字典的枚举循环中删除ConcurrentDictionary中的项吗?

red*_*alx 33 .net concurrency parallel-extensions

例如:

ConcurrentDictionary<string,Payload> itemCache = GetItems();

foreach(KeyValuePair<string,Payload> kvPair in itemCache)
{
    if(TestItemExpiry(kvPair.Value))
    {   // Remove expired item.
        Payload removedItem;
        itemCache.TryRemove(kvPair.Key, out removedItem);
    }
}
Run Code Online (Sandbox Code Playgroud)

显然,对于普通的Dictionary,这将引发异常,因为删除项会在枚举的生命周期中更改字典的内部状态.我的理解是,并非ConcurrentDictionary的情况,因为提供的IEnumerable处理内部状态更改.我明白了吗?有更好的模式可供使用吗?

Dan*_*Tao 35

我很奇怪你现在收到的两个答案似乎证实你不能这样做.我只是自己测试它,它工作正常,没有任何异常.

下面是我用来测试行为的代码,接下来是输出的摘录(当我按下'C'以清除a中的字典foreach并且S之后立即停止后台线程时).请注意,我对此施加了相当大的压力ConcurrentDictionary:每个尝试大约每15毫秒添加一个项目的16个线程计时器.

在我看来,这个类非常强大,如果你在多线程场景中工作,值得你注意.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;

namespace ConcurrencySandbox {
    class Program {
        private const int NumConcurrentThreads = 16;
        private const int TimerInterval = 15;

        private static ConcurrentDictionary<int, int> _dictionary;
        private static WaitHandle[] _timerReadyEvents;
        private static Timer[] _timers;
        private static volatile bool _timersRunning;

        [ThreadStatic()]
        private static Random _random;
        private static Random GetRandom() {
            return _random ?? (_random = new Random());
        }

        static Program() {
            _dictionary = new ConcurrentDictionary<int, int>();
            _timerReadyEvents = new WaitHandle[NumConcurrentThreads];
            _timers = new Timer[NumConcurrentThreads];

            for (int i = 0; i < _timerReadyEvents.Length; ++i)
                _timerReadyEvents[i] = new ManualResetEvent(true);

            for (int i = 0; i < _timers.Length; ++i)
                _timers[i] = new Timer(RunTimer, _timerReadyEvents[i], Timeout.Infinite, Timeout.Infinite);

            _timersRunning = false;
        }

        static void Main(string[] args) {
            Console.Write("Press Enter to begin. Then press S to start/stop the timers, C to clear the dictionary, or Esc to quit.");
            Console.ReadLine();

            StartTimers();

            ConsoleKey keyPressed;
            do {
                keyPressed = Console.ReadKey().Key;
                switch (keyPressed) {
                    case ConsoleKey.S:
                        if (_timersRunning)
                            StopTimers(false);
                        else
                            StartTimers();

                        break;
                    case ConsoleKey.C:
                        Console.WriteLine("COUNT: {0}", _dictionary.Count);
                        foreach (var entry in _dictionary) {
                            int removedValue;
                            bool removed = _dictionary.TryRemove(entry.Key, out removedValue);
                        }
                        Console.WriteLine("COUNT: {0}", _dictionary.Count);

                        break;
                }

            } while (keyPressed != ConsoleKey.Escape);

            StopTimers(true);
        }

        static void StartTimers() {
            foreach (var timer in _timers)
                timer.Change(0, TimerInterval);

            _timersRunning = true;
        }

        static void StopTimers(bool waitForCompletion) {
            foreach (var timer in _timers)
                timer.Change(Timeout.Infinite, Timeout.Infinite);

            if (waitForCompletion) {
                WaitHandle.WaitAll(_timerReadyEvents);
            }

            _timersRunning = false;
        }

        static void RunTimer(object state) {
            var readyEvent = state as ManualResetEvent;
            if (readyEvent == null)
                return;

            try {
                readyEvent.Reset();

                var r = GetRandom();
                var entry = new KeyValuePair<int, int>(r.Next(), r.Next());
                if (_dictionary.TryAdd(entry.Key, entry.Value))
                    Console.WriteLine("Added entry: {0} - {1}", entry.Key, entry.Value);
                else
                    Console.WriteLine("Unable to add entry: {0}", entry.Key);

            } finally {
                readyEvent.Set();
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

输出(摘录)

cAdded entry: 108011126 - 154069760   // <- pressed 'C'
Added entry: 245485808 - 1120608841
Added entry: 1285316085 - 656282422
Added entry: 1187997037 - 2096690006
Added entry: 1919684529 - 1012768429
Added entry: 1542690647 - 596573150
Added entry: 826218346 - 1115470462
Added entry: 1761075038 - 1913145460
Added entry: 457562817 - 669092760
COUNT: 2232                           // <- foreach loop begins
COUNT: 0                              // <- foreach loop ends
Added entry: 205679371 - 1891358222
Added entry: 32206560 - 306601210
Added entry: 1900476106 - 675997119
Added entry: 847548291 - 1875566386
Added entry: 808794556 - 1247784736
Added entry: 808272028 - 415012846
Added entry: 327837520 - 1373245916
Added entry: 1992836845 - 529422959
Added entry: 326453626 - 1243945958
Added entry: 1940746309 - 1892917475
Run Code Online (Sandbox Code Playgroud)

另请注意,基于控制台输出,看起来foreach循环锁定了试图向字典添加值的其他线程.(我可能错了,但我猜你会在"COUNT"行之间看到一堆"添加条目".)

  • @Peter Gfader:你看错了文档!`ConcurrentQueue`遍历快照; `ConcurrentDictionary`确实*不*:http://msdn.microsoft.com/en-us/library/dd287131(v = VS.100).aspx (9认同)
  • 实际上,看看mscorlib的反汇编,版本= 4.0.0.0(据我所知是最新版本),它绝对不会以任何方式使用Keys的快照.迭代器似乎是通过Enumerator的MoveNext方法中每个Node的m_next属性迭代存储在'm_buckets'中的持久Node数组...这似乎表明在最后会拾取任何新密钥.文件不清楚. (4认同)
  • 好的,删除这些最后的几条评论。我已经整理好了。拆卸是正确的,它不会在快照库上进行迭代,此后没有任何变化。“ rboardman”是指通过显式遍历“ Keys”属性(确实返回只读快照)在其自己的代码中进行“更改”的线程。 (2认同)

Mat*_*son 17

只是为了确认官方文档明确指出它是安全的:

从字典返回的枚举器可以安全地与字典的读写一起使用,但它并不代表字典的即时快照.通过枚举器公开的内容可能包含在调用GetEnumerator后对字典所做的修改.

  • 答案在于MSDN博客(遗憾的是不在文档中):"最大的变化是我们正在迭代"Keys"属性返回的内容,该属性返回给定点字典中键的快照.这意味着循环不会受到对字典的后续修改的影响,因为它在快照上运行." (3认同)
  • @Triynko您能给我该MSDN博客文章的链接吗?谢谢! (2认同)