Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class CacheItem
- {
- public void ExpensiveLoad()
- {
- // some expensive code
- }
- }
- public class Cache
- {
- static object SynchObj = new object();
- static Dictionary<string, CacheItem> Cache = new Dictionary<string, CacheItem>();
- static volatile List<string> CacheKeys = new List<string>();
- public CacheItem Get(string key)
- {
- List<string> keys = CacheKeys;
- if (!keys.Contains(key))
- {
- lock (SynchObj)
- {
- keys = CacheKeys;
- if (!keys.Contains(key))
- {
- CacheItem item = new CacheItem();
- item.ExpensiveLoad();
- Cache.Add(key, item);
- List<string> newKeys = new List<string>(CacheKeys);
- newKeys.Add(key);
- CacheKeys = newKeys;
- }
- }
- }
- return Cache[key];
- }
- }
- return Cache[key];
- _Cache.Add(key, item);
- public CacheItem Get(string key)
- {
- lock (SynchObj)
- {
- CacheItem item;
- if (!Cache.TryGetValue(key, out item))
- {
- item = new CacheItem();
- item.ExpensiveLoad();
- Cache.Add(key, item);
- }
- return item;
- }
- }
- static ConcurrentDictionary<string, CacheItem> Cache =
- new ConcurrentDictionary<string, CacheItem>(StringComparer.Ordinal);
- ...
- CacheItem item = Cache.GetOrAdd(key, key => ExpensiveLoad(key));
- static ConcurrentDictionary<string, Lazy<CacheItem>> Cache =
- new ConcurrentDictionary<string, Lazy<CacheItem>>(StringComparer.Ordinal);
- ...
- CacheItem item = Cache.GetOrAdd(key,
- new Lazy<CacheItem>(()=> ExpensiveLoad(key))
- ).Value;
- public class CacheItem
- {
- public void ExpensiveLoad()
- {
- // some expensive code
- }
- }
- public class Cache
- {
- private static object _SynchObj = new object();
- private static Dictionary<string, CacheItem> _Cache = new Dictionary<string, CacheItem>();
- private static ReadOnlyCollection<string> _CacheKeysReadOnly = new ReadOnlyCollection(new List<string>());
- public IList<string> CacheKeys
- {
- get
- {
- return _CacheKeysReadOnly;
- }
- }
- public CacheItem Get(string key)
- {
- CacheItem item = null;
- ReadOnlyCollection<string> keys = _CacheKeysReadOnly;
- if (!keys.Contains(key))
- {
- lock (_SynchObj)
- {
- keys = _CacheKeysReadOnly;
- if (!keys.Contains(key))
- {
- item = new CacheItem();
- item.ExpensiveLoad();
- _Cache.Add(key, item);
- List<string> newKeys = new List<string>(_CacheKeysReadOnly);
- newKeys.Add(key);
- _CacheKeysReadOnly = newKeys.AsReadOnly();
- }
- }
- }
- return item;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement