Skip to content

Instantly share code, notes, and snippets.

@manisero
Created November 23, 2017 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save manisero/8fa3a91c370e0d8609cb224ec2096ed8 to your computer and use it in GitHub Desktop.
Save manisero/8fa3a91c370e0d8609cb224ec2096ed8 to your computer and use it in GitHub Desktop.
Simple thread-safe cache spending minimum time in lock (thanks to Lazy).
public class ThreadSafeCache<TKey, TItem>
{
private readonly ConcurrentDictionary<TKey, Lazy<TItem>> _cache = new ConcurrentDictionary<TKey, Lazy<TItem>>();
private readonly object _lock = new object();
public TItem GetOrAdd(TKey key, Func<TKey, TItem> itemFactory)
{
Lazy<TItem> item;
if (!_cache.TryGetValue(key, out item))
{
lock (_lock)
{
item = _cache.GetOrAdd(key, x => new Lazy<TItem>(() => itemFactory(x)));
}
}
return item.Value;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment