Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Concurrent;
- namespace Common.Utilities
- {
- /// <summary>
- /// Very simple caching using a <seealso cref="System.Collections.Concurrent.ConcurrentDictionary"/>
- /// </summary>
- public class SimpleCache
- {
- static SimpleCache _default = new SimpleCache();
- public static SimpleCache Default
- {
- get { return _default; }
- }
- readonly ConcurrentDictionary<string, object> s_cache = new ConcurrentDictionary<string, object>();
- /// <summary>
- /// Returns the cached item or call the valueFactory() delegate to insert the results into the cache
- /// </summary>
- public T GetOrAdd<T>(string key, Func<string, T> valueFactory, bool enabled = true) where T : class
- {
- if (!enabled)
- return valueFactory(key);
- object raw = s_cache.GetOrAdd(key, valueFactory: (arg) =>
- {
- return valueFactory(arg);
- });
- T ret = raw as T;
- return ret;
- }
- /// <summary>
- /// Returns the cached item or call the valueFactory() delegate to insert the results into the cache
- /// </summary>
- public object GetOrAdd(string key, Func<string, object> valueFactory, bool enabled = true)
- {
- return GetOrAdd<object>(key, valueFactory, enabled);
- }
- public void Clear()
- {
- s_cache.Clear();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment