我是否需要在并发字典的AddOrUpdate中锁定?

时间:2015-05-14 20:33:01

标签: c# .net .net-4.0 locking concurrentdictionary

在我班上我有

public static ConcurrentDictionary<string, HashSet<string>> ConnectedUserConnections = new ConcurrentDictionary<string, HashSet<string>>();

添加或更新时,我应该通过以下方式更新:

ConnectedUserConnections.AddOrUpdate(userId, new HashSet<string>(), (key, existingVal) =>
                {
                    existingVal.Add(connectionId);
                    return existingVal;
                });

ConnectedUserConnections.AddOrUpdate(userId, new HashSet<string>(), (key, existingVal) =>
                {
                   lock(ConnectedUserConnections)

                    {
                        existingVal.Add(connectionId);
                        return existingVal;
                    }
                });

非常感谢所有人。

1 个答案:

答案 0 :(得分:0)

查看参考来源的public TValue AddOrUpdate(TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory)

 while (true)
 {
     TValue oldValue;
     if (TryGetValue(key, out oldValue))
     //key exists, try to update
     {
         newValue = updateValueFactory(key, oldValue);
         if (TryUpdate(key, newValue, oldValue))

TryGetValue之前没有锁定,因此如果key已有值,则多个线程可以到达TryGetValue,执行它,返回true ,同时执行updateValueFactory(您的方法)并尝试添加existingVal.Add(connectionId); ...

是的,你确实需要一个lock