【问题标题】:Do I need a lock in AddOrUpdate of a concurrent dictionary?我需要锁定并发字典的 AddOrUpdate 吗?
【发布时间】:2015-05-14 20:33:00
【问题描述】:

在我的课堂上

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;
                    }
                });

非常感谢大家。

【问题讨论】:

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


    【解决方案1】:

    通过查看参考源中的public TValue AddOrUpdate(TKey key, Func&lt;TKey, TValue&gt; addValueFactory, Func&lt;TKey, TValue, TValue&gt; 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多