Created
November 23, 2017 22:08
-
-
Save manisero/8fa3a91c370e0d8609cb224ec2096ed8 to your computer and use it in GitHub Desktop.
Simple thread-safe cache spending minimum time in lock (thanks to Lazy).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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