C# 如何在此对象中实现AddOrUpdate()中的Func:ConcurrentDictionary<;int,List<;MyObject>&燃气轮机;
如何在ConcurrentDictionary中实现C# 如何在此对象中实现AddOrUpdate()中的Func:ConcurrentDictionary<;int,List<;MyObject>&燃气轮机;,c#,multithreading,concurrency,concurrentdictionary,C#,Multithreading,Concurrency,Concurrentdictionary,如何在ConcurrentDictionary中实现AddorUpdate,以便在该值为集合时正确更新该值 我担心的是,由于TValue是一种引用类型,我可能会遇到在竞争条件下多次调用TValue的情况。我会自己测试这个,但是我的语法是错误的,所以我不能继续 我必须改变什么才能让这一切顺利进行 public class TrustList : ConcurrentDictionary<int, List<TrustRelationshipDetail>>
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...
);
}
}
公共类信任列表:ConcurrentDictionary
{
public void AddOrUpdateTrustDetail(信任关系详细信息)
{
List detailList=新列表();
详细列表。添加(详细信息);
this.AddOrUpdate(detail.HierarchyDepth,detailList,(key,oldValue)=>
添加(细节)/添加或更新()的目的是用新值替换任何现有值
由于您只需要获取现有值(以便随后对其进行修改),因此需要GetOrAdd()
:
this.GetOrAdd(detail.HierarchyDepth,new ConcurrentBag())
.增加(详情);
那是行不通的,因为List
不是线程安全的。这个答案在很多方面都是完美的。我要花很长时间才能看清楚(如果有的话)
this.GetOrAdd(detail.HierarchyDepth, new ConcurrentBag<TrustRelationshipDetail>())
.Add(detail);