2014-10-01 30 views
1

它,我想創造一種推廣方法是這樣的:Dictionarry <T,List<U>> Extention線程安全法「AddToList」是創建一個列表,如果不存在

public static void AddToList<T,U>(
     this Dictionary<T,List<U>> dictionary, T key, U value) 
{ 
    //If the list exist, add to the list. 
    //Else Create the list and add the item. 
} 

這是我試過到目前爲止:

public static void AddToList<T,U>(this Dictionary<T,List<U>> dictionary, T key, U value) 
{ 
    if (!dictionary.ContainsKey(key) || dictionary[key] == null) 
    { 
     dictionary[key] = new List<U>(); 
    } 
    dictionary[key].Add(value); 
} 

我該如何處理線程安全?

+0

要鎖定迪科的訪問,以便圍繞AddList的通話 – Thomas 2014-10-01 13:36:52

回答

3

如果您需要線程安全性,則可以改爲使用ConcurrentDictionary

var dictionary = new ConcurrentDictionary<T, List<U>>(); 
List<U> values = dictionary.GetOrAdd(key, _ => new List<U>()); 

一些其他注意事項:

  1. 使用TryGetValue而不是GetOrAdd以避免造成不必要的List<U>如果你不是在將一個值添加到列表的方法。
  2. 這隻能解決創建List<U>時的線程安全問題。您仍然需要解決單個列表上的操作。
0

我會開始使用ConcurrentDictionary<TKey, TValue>,它負責將不存在的列表添加到字典中的線程安全性。

請注意,您始終將項目添加到列表中,而且您不檢查項目是否已經在列表中。如果你想要的話,那麼這是保證線程安全的另一個額外步驟。

public static void AddToList<T, U>(
    this ConcurrentDictionary<T, List<U>> dictionary, 
    T key, 
    U value 
) { 
    var list = dictionary.GetOrAdd(key, k => new List<U>()); 
    list.Add(value); 
} 
+0

你現在添加項目,從多個線程,這將不會是安全的公共列表。 – Servy 2014-10-01 14:11:04