如何在C#中获取ConcurrentDictionary的即时快照?

Ram*_*amy 2 c# multithreading concurrentdictionary

MSDN声明从字典返回的枚举器不代表字典的时刻快照.虽然在多线程环境中很少需要它,但如果有人想要,获取ConcurrentDictionary的即时快照的最佳方法是什么?

apo*_*pse 7

只需调用ToArray()方法.

这是一个源代码:

    /// <summary>
    /// Copies the key and value pairs stored in the <see cref="ConcurrentDictionary{TKey,TValue}"/> to a
    /// new array.
    /// </summary>
    /// <returns>A new array containing a snapshot of key and value pairs copied from the <see
    /// cref="ConcurrentDictionary{TKey,TValue}"/>.</returns>
    [SuppressMessage("Microsoft.Concurrency", "CA8001", Justification = "ConcurrencyCop just doesn't know about these locks")]
    public KeyValuePair<TKey, TValue>[] ToArray()
    {
        int locksAcquired = 0;
        try
        {
            AcquireAllLocks(ref locksAcquired);
            int count = 0;
            checked
            {
                for (int i = 0; i < m_tables.m_locks.Length; i++)
                {
                    count += m_tables.m_countPerLock[i];
                }
            }

            KeyValuePair<TKey, TValue>[] array = new KeyValuePair<TKey, TValue>[count];

            CopyToPairs(array, 0);
            return array;
        }
        finally
        {
            ReleaseLocks(0, locksAcquired);
        }
    }
Run Code Online (Sandbox Code Playgroud)

  • 你甚至可以将它链接到一个 `foo.ToArray().ToDictionary(x=&gt;x.Key, x=&gt;x.Value);` 以将它恢复为字典形式。(不要只做 `foo.DoDictionary()` 否则它会使用 `.GetEnumerator()` 函数而不是 `.ToArray()` 函数作为数据源) (2认同)