ConcurrentDictionary和Dictionary对比

Dictionary非线程安全集合

代码测试会报错:集合已经改变

    public class ConcurrentDictionaryTest
    {
        public void Run()
        {
            Dictionary<string, int> dic = new Dictionary<string, int>();
            Task.Run(()=> {
                while (true)
                {
                    foreach (var item in dic)
                    {
                        Console.WriteLine(item.Key);
                    }
                }
            });

            while (true)
            {
                for (int i = 0; i < 10000; i++)
                {
                    dic[i.ToString()] = i;
                }
            }
        }
    }

ConcurrentDictionary线程安全集合

直接上代码测:这个不会报错。

    public class ConcurrentDictionaryTest
    {
        public void Run()
        {
            ConcurrentDictionary<string, int> dic = new ConcurrentDictionary<string, int>();
            Task.Run(()=> {
                while (true)
                {
                    foreach (var item in dic)
                    {
                        Console.WriteLine(item.Key);
                    }
                }
            });

            while (true)
            {
                for (int i = 0; i < 10000; i++)
                {
                    dic[i.ToString()] = i;
                }
            }
        }
    }
ConcurrentDictionary里面会有细粒度锁定,所以在增删查改基本不需要锁控制。

关于他们的速率看另外一篇微博:写入速率
Dictionary快点,但在加锁读取情况ConcurrentDictionary更快。
代码详见:https://blog.csdn.net/conquerwave/article/details/50815557

猜你喜欢

转载自www.cnblogs.com/zhuyapeng/p/12754829.html