private class ThreadsafeMemoizeCache<TArgument, TResult>
{
private Dictionary<TArgument, TResult> cache = new Dictionary<TArgument, TResult>();
public TResult GetOrAdd(TArgument key, Func<TArgument, TResult> valueFactory)
{
TResult result;
if (cache.TryGetValue(key, out result))
{
return result;
}
lock (this)
{
if (!cache.TryGetValue(key, out result))
{
result = valueFactory(key);
Dictionary<TArgument, TResult> newCache = new Dictionary<TArgument, TResult>(cache);
newCache.Add(key, result);
cache = newCache;
}
}
return result;
}
}
lock (this)
{
if (cache.TryGetValue(key, out result))
{
return result;
}
if (!cache.TryGetValue(key, out result))
{
result = valueFactory(key);
Dictionary<TArgument, TResult> newCache = new Dictionary<TArgument, TResult>(cache);
newCache.Add(key, result);
cache = newCache;
}
}
private class ThreadsafeMemoizeCache<TArgument, TResult>
{
private readonly Dictionary<TArgument, TResult> _internalCache = new Dictionary<TArgument, TResult>();
private readonly object _internalCacheLocker = new object();
public TResult GetOrAdd(TArgument key, Func<TArgument, TResult> valueFactory)
{
lock (_internalCacheLocker)
{
TResult result;
if (_internalCache.TryGetValue(key, out result))
return result;
result = valueFactory(key);
_internalCache.Add(key, result);
return result;;
}
}
}
var cache = new ThreadsafeMemoizeCache<string, string>();
cache.GetOrAdd("1", (arg) => string.Empty);
cache.GetOrAdd("1", (arg) => string.Empty);