【发布时间】:2017-02-13 13:56:21
【问题描述】:
我想创建一个新类来包装当前的 .net ConcurrentDictionary,以便确保 GetOrAdd\AddOrUpdate 的 Add 委托只被调用一次。我在网上看到了一些解决方案,主要的一个是用惰性包装 TValue 以便可以添加许多惰性项,但只有一个能够存活并调用它的值工厂。
这是我想出的:
public class LazyConcurrentDictionary<TKey, TValue>
{
private readonly ConcurrentDictionary<TKey, Lazy<TValue>> concurrentDictionary;
public LazyConcurrentDictionary()
{
this.concurrentDictionary = new ConcurrentDictionary<TKey, Lazy<TValue>>();
}
public TValue GetOrAdd(TKey key, Func<TKey, TValue> valueFactory)
{
var lazyResult = this.concurrentDictionary.GetOrAdd(key, k => new Lazy<TValue>(() => valueFactory(k), LazyThreadSafetyMode.ExecutionAndPublication));
return lazyResult.Value;
}
public TValue AddOrUpdate(TKey key, Func<TKey, TValue> addFactory, Func<TKey, TValue> updateFactory)
{
// this one fails with "Cannot convert lambda expression to type 'System.Lazy' because it is not a delegate type"
var lazyResult = this.concurrentDictionary.AddOrUpdate(key, (k) => new Lazy<TValue>( () => addFactory(k), LazyThreadSafetyMode.ExecutionAndPublication), updateFactory);
return lazyResult.Value;
}
}
我的问题在于 AddOrUpdate 签名,我收到“无法将 lambda 表达式转换为类型 'System.Lazy',因为它不是委托类型”
我做错了什么?
【问题讨论】:
标签: c# .net lazy-evaluation concurrentdictionary