Why does ConcurrentDictionary.GetOrAdd(key, valueFactory) allow the valueFactory to be invoked twice?

前端 未结 2 687
梦谈多话
梦谈多话 2020-12-08 04:36

I am using a concurrent dictionary as a thread-safe static cache and noticed the following behavior:

From the MSDN docs on GetOrAdd:

If you ca

2条回答
  •  一整个雨季
    2020-12-08 05:18

    You could use a dictionary that is typed like this: ConcurrentDictionary>, and then the your value factory would return a Lazy object that has been initialized with LazyThreadSafetyMode.ExecutionAndPublication, which is the default option used by Lazy if you don't specify it. By specifying the LazyThreadSafetyMode.ExecutionAndPublication you are telling Lazy only one thread may initialize and set the value of the object.

    This results in the ConcurrentDictionary only using one instance of the Lazy object, and the Lazy object protects more than one thread from initializing its value.

    i.e.

    var dict = new ConcurrentDictionary>();
    dict.GetOrAdd(key,  
        (k) => new Lazy(valueFactory)
    );
    

    The downside then is you'll need to call *.Value every time you are accessing an object in the dictionary. Here are some extensions that'll help with that.

    public static class ConcurrentDictionaryExtensions
    {
        public static TValue GetOrAdd(
            this ConcurrentDictionary> @this,
            TKey key, Func valueFactory
        )
        {
            return @this.GetOrAdd(key,
                (k) => new Lazy(() => valueFactory(k))
            ).Value;
        }
    
        public static TValue AddOrUpdate(
            this ConcurrentDictionary> @this,
            TKey key, Func addValueFactory,
            Func updateValueFactory
        )
        {
            return @this.AddOrUpdate(key,
                (k) => new Lazy(() => addValueFactory(k)),
                (k, currentValue) => new Lazy(
                    () => updateValueFactory(k, currentValue.Value)
                )
            ).Value;
        }
    
        public static bool TryGetValue(
            this ConcurrentDictionary> @this,
            TKey key, out TValue value
        )
        {
            value = default(TValue);
    
            var result = @this.TryGetValue(key, out Lazy v);
    
            if (result) value = v.Value;
    
            return result;
       }
    
       // this overload may not make sense to use when you want to avoid
       //  the construction of the value when it isn't needed
       public static bool TryAdd(
           this ConcurrentDictionary> @this,
           TKey key, TValue value
       )
       {
           return @this.TryAdd(key, new Lazy(() => value));
       }
    
       public static bool TryAdd(
           this ConcurrentDictionary> @this,
           TKey key, Func valueFactory
       )
       {
           return @this.TryAdd(key,
               new Lazy(() => valueFactory(key))
           );
       }
    
       public static bool TryRemove(
           this ConcurrentDictionary> @this,
           TKey key, out TValue value
       )
       {
           value = default(TValue);
    
           if (@this.TryRemove(key, out Lazy v))
           {
               value = v.Value;
               return true;
           }
           return false;
       }
    
       public static bool TryUpdate(
           this ConcurrentDictionary> @this,
           TKey key, Func updateValueFactory
       )
       {
           if (!@this.TryGetValue(key, out Lazy existingValue))
               return false;
    
           return @this.TryUpdate(key,
               new Lazy(
                   () => updateValueFactory(key, existingValue.Value)
               ),
               existingValue
           );
       }
    }
    

提交回复
热议问题