Tag: 并发集合

SynchronizedCollection <T>和其他并发集合有什么区别?

SynchronizedCollection<T>和System.Collections.Concurrent命名空间中的并发集合是如何不同的,除了Concurrent Collections是命名空间, SynchronizedCollection<T>是类? SynchronizedCollection<T>和并发集合中的所有类都提供了线程安全的集合。 我该如何决定何时使用一个,为什么?

为什么ConcurrentBag <T>在.Net(4.0)中很慢? 我做错了吗?

在开始一个项目之前,我写了一个简单的testing来比较来自(System.Collections.Concurrent)的ConcurrentBag相对于locking和列表的性能。 我感到非常惊讶的是,ConcurrentBag比locking一个简单的列表要慢10倍以上。 据我所知,当读者和作者是同一个线程时,ConcurrentBag效果最好。 但是,我没有想到它的性能会比传统的锁更糟糕。 我已经运行了一个testing,用两个Parallel for循环写入和从列表/包中读取。 但是,写本身就performance出巨大的差异: private static void ConcurrentBagTest() { int collSize = 10000000; Stopwatch stopWatch = new Stopwatch(); ConcurrentBag<int> bag1 = new ConcurrentBag<int>(); stopWatch.Start(); Parallel.For(0, collSize, delegate(int i) { bag1.Add(i); }); stopWatch.Stop(); Console.WriteLine("Elapsed Time = {0}", stopWatch.Elapsed.TotalSeconds); } 在我的盒子里,这需要3-4秒的时间才能运行,相比之下,这个代码是0.5 – 0.9秒: private static void LockCollTest() { int collSize = 10000000; object list1_lock=new […]

ConcurrentDictionary AddOrUpdate

我正在尝试使用Dictionary重新编写一些代码来使用ConcurrentDictionary。 我已经回顾了一些例子,但是我仍然无法实现AddOrUpdate函数。 这是原始的代码: dynamic a = HttpContext; Dictionary<int, string> userDic = this.HttpContext.Application["UserSessionList"] as Dictionary<int, String>; if (userDic != null) { if (useDic.ContainsKey(authUser.UserId)) { userDic.Remove(authUser.UserId); } } else { userDic = new Dictionary<int,string>(); } userDic.Add(authUser.UserId, a.Session.SessionID.ToString()); this.HttpContext.Application["UserDic"] = userDic; 我不知道要为更新部分添加什么: userDic.AddOrUpdate(authUser.UserId, a.Session.SessionID.ToString(), /*** what to add here? ***/); 任何指针将不胜感激。