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

标签 c# multithreading concurrentdictionary

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

最佳答案

只需调用 ToArray() 方法。

这是一个source code :

    /// <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);
        }
    }

关于c# - 如何在 C# 中获取 ConcurrentDictionary 的即时快照?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43924965/

相关文章:

c# - Folder.Bind - "Id is malformed"- Exchange Web 服务托管 API

c - 多个互斥锁如何工作?

c# - 一种使我的 Parallel.ForEach 线程安全的更好方法?

c# - .NET ConcurrentDictionary.ToArray() 参数异常

c# - 防伪 token 可重复使用

c# - SQL Server - 以编程方式发现存储过程的返回值

c# - 使用 XDocument 查找元素属性

Python 3 - 在用户将鼠标悬停在 GUI 窗口上之前,主线程未检测到后台线程中的键盘中断

java - 如何在引用循环变量的匿名类中在循环中创建线程?

c# - 什么能比并发集合更好地解决这种多线程场景