Dictionary >扩展线程安全的方法'AddToList',如果不存在则创建列表

问题描述 投票:1回答:2

我想创建这样的扩展方法:

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);
}

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

c# extension-methods
2个回答
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);
}
© www.soinside.com 2019 - 2024. All rights reserved.