andrew4582

Simple Cache

Mar 25th, 2015
384
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.28 KB | None | 0 0
  1. using System;
  2. using System.Collections.Concurrent;
  3.  
  4. namespace Common.Utilities
  5. {
  6.     /// <summary>
  7.     /// Very simple caching using a <seealso cref="System.Collections.Concurrent.ConcurrentDictionary"/>
  8.     /// </summary>
  9.     public class SimpleCache
  10.     {
  11.         static SimpleCache _default = new SimpleCache();
  12.  
  13.         public static SimpleCache Default
  14.         {
  15.             get { return _default; }
  16.         }
  17.  
  18.         readonly ConcurrentDictionary<string, object> s_cache = new ConcurrentDictionary<string, object>();
  19.  
  20.         /// <summary>
  21.         /// Returns the cached item or call the valueFactory() delegate to insert the results into the cache
  22.         /// </summary>
  23.         public T GetOrAdd<T>(string key, Func<string, T> valueFactory, bool enabled = true) where T : class
  24.         {
  25.             if (!enabled)
  26.                 return valueFactory(key);
  27.  
  28.             object raw = s_cache.GetOrAdd(key, valueFactory: (arg) =>
  29.             {
  30.                 return valueFactory(arg);
  31.             });
  32.  
  33.             T ret = raw as T;
  34.             return ret;
  35.         }
  36.  
  37.         /// <summary>
  38.         /// Returns the cached item or call the valueFactory() delegate to insert the results into the cache
  39.         /// </summary>
  40.         public object GetOrAdd(string key, Func<string, object> valueFactory, bool enabled = true)
  41.         {
  42.             return GetOrAdd<object>(key, valueFactory, enabled);
  43.         }
  44.  
  45.         public void Clear()
  46.         {
  47.             s_cache.Clear();
  48.         }
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment