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? ***/); 

任何指针将不胜感激。

你需要传递一个Func ,它返回在更新的时候存储在字典中的值。 我想你的情况(因为你不区分添加和更新),这将是:

 var sessionId = a.Session.SessionID.ToString(); userDic.AddOrUpdate( authUser.UserId, sessionId, (key, oldValue) => sessionId); 

也就是说, Func总是返回sessionId,这样Add和Update都会设置相同的值。

顺便说一句: MSDN页面上有一个示例。

我希望,我没有错过任何你的问题,但为什么不是这样? 这是更容易,primefaces和线程安全(见下文)。

 userDic[authUser.UserId] = sessionId; 

将键/值对无条件地存储到字典中,如果键已经存在,则覆盖该键的任何值:使用索引器的setter

(请参阅: http : //blogs.msdn.com/b/pfxteam/archive/2010/01/08/9945809.aspx )

索引器也是primefaces的。 如果你传递一个函数,它可能不是:

所有这些操作都是primefaces的,并且对于ConcurrentDictionary上的所有其他操作都是线程安全的。 每个操作的primefaces性唯一的警告是接受委托的人,即AddOrUpdate和GetOrAdd。 这些代表是在锁之外调用的

请参阅: http : //blogs.msdn.com/b/pfxteam/archive/2010/01/08/9945809.aspx

我结束了实现一个扩展方法:

 static class ExtensionMethods { // Either Add or overwrite public static void AddOrUpdate<K, V>(this ConcurrentDictionary<K, V> dictionary, K key, V value) { dictionary.AddOrUpdate(key, value, (oldkey, oldvalue) => value); } } 

对于那些感兴趣的人,我目前正在实施一个案例,这是一个很好的例子,使用“oldValue”又名现有的价值,而不是强迫一个新的(我个人不喜欢“oldValue”这个词,因为它不是当它是在一个并行线程内创build了几个处理器之前)。

 dictionaryCacheQueues.AddOrUpdate( uid, new ConcurrentQueue<T>(), (existingUid, existingValue) => existingValue );