【问题标题】:How should I implement the Func in AddOrUpdate() in this object: ConcurrentDictionary<int, List<MyObject>>我应该如何在这个对象的 AddOrUpdate() 中实现 Func: ConcurrentDictionary<int, List<MyObject>>
【发布时间】:2012-10-18 02:54:07
【问题描述】:

如何在 ConcurrentDictionary 中实现 AddorUpdate 以便我可以正确更新该值(如果该值是一个集合)?

我担心的是,由于 TValue 是一种引用类型,我可能会遇到在竞争条件下多次调用 TValue 的情况。我会自己测试一下,但我的语法错误,所以我无法继续。

我必须改变什么才能使它工作?

   public class TrustList :  ConcurrentDictionary<int, List<TrustRelationshipDetail>>
    {
        public void AddOrUpdateTrustDetail(TrustRelationshipDetail detail)
        {
            List<TrustRelationshipDetail> detailList = new List<TrustRelationshipDetail>();
            detailList.Add(detail);

            this.AddOrUpdate(detail.HierarchyDepth, detailList, (key, oldValue) =>   
            oldValue.Add(detail)  // <--- Compiler doesn't like this, and I think this may cause duplicates if this were to be called...
           );
        }
    }

【问题讨论】:

  • 那行不通,因为List&lt;T&gt; 不是线程安全的。

标签: c# multithreading concurrency concurrentdictionary


【解决方案1】:

AddOrUpdate() 的目的是用新值替换任何现有值。

由于您只需要获取现有值(以便随后对其进行修改),因此您需要GetOrAdd()

this.GetOrAdd(detail.HierarchyDepth, new ConcurrentBag<TrustRelationshipDetail>())
        .Add(detail);

【讨论】:

  • 这个答案在很多方面都很完美。我要花很长时间才能清楚地看到它(如果有的话)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-07
  • 2011-03-20
相关资源
最近更新 更多