2015-05-25 73 views
2

我發現這個擴展爲C#將GetOrAdd轉換爲Lazy,並且我想爲AddOrUpdate執行相同的操作。ConcurrentDictionary Lazy AddOrUpdate

有人可以幫我將此轉換爲AddOrUpdate?

public static class ConcurrentDictionaryExtensions 
{ 
    public static TValue LazyGetOrAdd<TKey, TValue>(
     this ConcurrentDictionary<TKey, Lazy<TValue>> dictionary, 
     TKey key, 
     Func<TKey, TValue> valueFactory) 
    { 
     if (dictionary == null) throw new ArgumentNullException("dictionary"); 
     var result = dictionary.GetOrAdd(key, new Lazy<TValue>(() => valueFactory(key))); 
     return result.Value; 
    } 


} 

回答

1

它是這樣的:

public static TValue AddOrUpdate<TKey, TValue>(this ConcurrentDictionary<TKey, Lazy<TValue>> dictionary, TKey key, Func<TKey, TValue> addValueFactory, Func<TKey, TValue, TValue> updateValueFactory) 
{ 
    if (dictionary == null) throw new ArgumentNullException("dictionary"); 
    var result = dictionary.AddOrUpdate(key, new Lazy<TValue>(() => addValueFactory(key)), (key2, old) => new Lazy<TValue>(() => updateValueFactory(key2, old.Value))); 
    return result.Value; 
} 

注意的第二個參數的格式:返回一個新Lazy<>對象的委託......所以從某個角度來看,雙懶惰: - )

+0

有沒有機會向我展示如何使用它的示例? ConcurrentDictionary.AddOrUpdate(CustomerID,1,(k,v)=> v + 1); –

+0

我認爲這可能就是它。字典.LazyAddOrUpdate(1,(ka)=> 1,(k,v)=> v + 1); –

+1

@andre是的你是對的 – xanatos