如何在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...
);
}
}
答案 0 :(得分:2)
AddOrUpdate()
的目的是用新值替换任何现有值。
由于您只需要获取现有值(然后进行修改),您需要GetOrAdd()
:
this.GetOrAdd(detail.HierarchyDepth, new ConcurrentBag<TrustRelationshipDetail>())
.Add(detail);