ConcurrentDictionary的使用



一、ConcurrentDictionary<TKey, TValue>的理解


1、表示可由多个线程同时访问的键/值对的线程安全集合。

2、ConcurrentDictionary是.net4.0推出的一套线程安全集合里的其中一个,和它一起被发行的还有

ConcurrentStack,ConcurrentQueue等类型,它们的单线程版本(线程不安全的,Queue,Stack,Dictionary)。

3、用法同Dictionary很多相同,但是多了一些方法。ConcurrentDictionary 属于System.Collections.Concurrent 命名空间



二、ConcurrentDictionary的实例


    public interface IGetLogger
    {
        Logger GetLogger(string cmdId);
    }

    public class ConcurrentDictionaryLogger : IGetLogger
    {
        ConcurrentDictionary<string, Logger> loggreDic = new ConcurrentDictionary<string, Logger>();
        public Logger GetLogger(string cmdId)
        {
            if (!loggreDic.ContainsKey(cmdId))
            {
                loggreDic.TryAdd(cmdId, LogManager.GetLogger(string.Format("AAA.{0}", cmdId)));
            }
            return loggreDic[cmdId];
        }
    }

    public static void Main()
    {
            IGetLogger conLogger = new ConcurrentDictionaryLogger();

            IGetLogger lockerLogger = new LockerDictionaryLogger();

            CodeTimer.Time("使用ConcurrentDictionary", 1000000, () =>
            {
                ThreadPool.QueueUserWorkItem(o =>
                {
                    try
                    {
                        var logger = conLogger.GetLogger("AAA");
                        if (logger == null)
                        {
                            Console.WriteLine(string.Format("第{0}个线程获取到的值是 NULL", o));
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("第{0}个线程出现问题, {1}", o, ex.Message));
                    }
                });
         });
   }



文章转载自:  ConcurrentDictionary与Dictionary的区别有哪些  http://www.studyofnet.com/news/1068.html


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值