C# 字典<;T、 列表<;U>&燃气轮机;扩展线程安全方法&x27;地址列表';如果列表不存在,则创建该列表

C# 字典<;T、 列表<;U>&燃气轮机;扩展线程安全方法&x27;地址列表';如果列表不存在,则创建该列表,c#,extension-methods,C#,Extension Methods,我想创建如下扩展方法: 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. } publicstaticvoidaddtolist(这个字典,T键,U值)

我想创建如下扩展方法:

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.
}
publicstaticvoidaddtolist(这个字典,T键,U值)
{
//如果列表存在,请添加到列表中。
//否则,创建列表并添加项目。
}
这就是我迄今为止所尝试的:

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);
}
publicstaticvoidaddtolist(这个字典,T键,U值)
{
if(!dictionary.ContainsKey(key)| | dictionary[key]==null)
{
字典[键]=新列表();
}
字典[键]。添加(值);
}

使用此方法如何处理线程安全性?

如果需要线程安全性,可以使用
ConcurrentDictionary

var dictionary = new ConcurrentDictionary<T, List<U>>();
List<U> values = dictionary.GetOrAdd(key, _ => new List<U>());
var dictionary=新的ConcurrentDictionary();
List values=dictionary.GetOrAdd(key,=>newlist());
一些补充说明:

  • 如果不使用将向列表中添加值的方法,请使用
    TryGetValue
    而不是
    GetOrAdd
    ,以避免创建不必要的
    列表
  • 这只解决了创建
    列表的线程安全问题。您仍然需要处理单个列表上的操作

  • 我将开始使用
    ConcurrentDictionary
    ,它负责将不存在的列表添加到字典中的线程安全性

    请注意,您总是将项目添加到列表中,而不是检查项目是否已在列表中。如果您需要,那么这是保证线程安全的另一个额外步骤

    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);
    }
    
    publicstaticvoidaddtolist(
    这本词典,
    T键,
    U值
    ) {
    var list=dictionary.GetOrAdd(key,k=>newlist());
    列表。添加(值);
    }
    
    要锁定dico中的访问权限,在调用AddList时,您现在要从多个线程将项目添加到公共列表中,这是不安全的。