2012-10-18 27 views
1

如何在ConcurrentDictionary中實現AddorUpdate,以便我可以正確更新值,如果該值爲集合?如何在此對象的AddOrUpdate()中實現Func:ConcurrentDictionary <int,列表<MyObject>>

我擔心的是,由於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

這是行不通的,因爲'名單'是不是線程安全的。 – SLaks

回答

2

AddOrUpdate()目的是取代任何現有的值與新的值。

既然你只需要得到現有的值(爲了然後修改它),你想GetOrAdd()

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

這個答案在很多方面都很完美。它會讓我永遠清楚地看到它(如果有的話) – LamonteCristo