ConcurrentDictionary的AddOrUpdate方法

https://msdn.microsoft.com/zh-cn/library/ee378665(v=vs.110).aspx

此方法有一共有2个,现在只讨论其中一个

public TValue AddOrUpdate(
TKey key,
TValue addValue,
Func<TKey, TValue, TValue> updateValueFactory
)

Parameters 参数说明

key 参数名称    【此参数不允许为null】
Type: TKey 参数类型
The key to be added or whose value should be updated 需要添加或者更新的key


addValue 参数名称
Type: TValue 参数类型
The value to be added for an absent key 和新key匹配的value


updateValueFactory 参数名称    【此参数不允许为null】
Type: System.Func<TKey, TValue, TValue> 参数类型
The function used to generate a new value for an existing key based on the key's existing value 此函数用来基于已有的key的value来生成新的值


Return Value 返回值
Type: TValue 返回值的类型
The new value for the key. This will be either be addValue (if the key was absent) or the result of updateValueFactory (if the key was present).

key对应的新value,可能是新添加的,也可能是更新的

假定目前有一个ConcurrentDictionary<string, Dictionary<string, Color>> dictionary,需要给它添加新的值

方法1:使用委托,写一个符合委托签名的方法

private Dictionary<string,Color> Method(string deviceId,Dictionary<string,Color> dic)
{
return dic;
}

调用的时候,       dictionary.AddOrUpdate(warningInfo.DeviceID, dic, Method);   //将Method作为参数进行传递

方法2:使用匿名委托

dictionary.AddOrUpdate(warningInfo.DeviceID, dic, delegate(string deviceId,Dictionary<string,Color> dic1)
{
return dic1;
});

方法3:直接使用lambda表达式

 dictionary.AddOrUpdate(warningInfo.DeviceID, dic, (key, value) => value);

假如有多个ConcurrentDictionary的变量,都需要使用AddOrUpdate函数,并且第三个参数updateValueFactory的逻辑相同【目前假设逻辑仅仅是返回Value的值】

可以将updateValueFactory抽象成一个泛型方法来使用

 /// <summary>
    /// GenericMethod类,用于存放泛型方法[但是这个类本身不是泛型的]
    /// </summary>
    public class GenericMethod
    {
        /// <summary>
        ///  System.Collections.Concurrent.ConcurrentDictionary类中AddOrUpdate方法中的第三个参数对应的一个泛型方法
        ///  目前的AddOrUpdate方法中的第三个三处Func委托只需要返回Value就可以了,不需要做其他的处理
        /// </summary>
        /// 参数
        /// <param name="key">第一个参数</param>
        /// <param name="value">第二个参数</param>
        /// 类型参数
        /// <typeparam name="TKey">第一个参数的类型</typeparam>
        /// <typeparam name="TValue">第二个参数的类型</typeparam>
        /// <returns></returns>
        public static TValue UpdateValueFactory<TKey, TValue>(TKey key, TValue value)
        {
            return value;
        }
    }

转载于:https://www.cnblogs.com/chucklu/p/4468057.html

原文地址:https://www.cnblogs.com/zbliao/p/12935753.html