【发布时间】: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<T>不是线程安全的。
标签: c# multithreading concurrency concurrentdictionary