Skip to content

Instantly share code, notes, and snippets.

@butaji
Created April 6, 2012 20:05
Show Gist options
  • Save butaji/2322582 to your computer and use it in GitHub Desktop.
Save butaji/2322582 to your computer and use it in GitHub Desktop.
Simple C# cache helper
public class Cache
{
static readonly Dictionary<string, object> _cache = new Dictionary<string, object>();
public static T Run<T>(Func<T> func, params object[] prms)
{
var key = GetKey(func, prms);
if (!_cache.ContainsKey(key) || !(_cache[key] is T))
_cache.Add(key, func());
return (T)_cache[key];
}
private static string GetKey<T>(Func<T> func, params object[] prms)
{
var method = func.Method.DeclaringType + "." + func.Method.Name;
var type = typeof(T).FullName;
return string.Format("{0}_{1}_{2}", method, type, string.Join("_", prms));
}
}
static void Main()
{
var result = Cache.Run(() => GetCustomerInfos(productId,id), productId, id);
}
@hodzanassredin
Copy link

я бы еще добавил переменную DisableCache

@butaji
Copy link
Author

butaji commented Apr 8, 2012

можно сжульничать и писать DateTime.Now.Ticks вместо params

@hodzanassredin
Copy link

Не я хочу например
if Debug:
CacheDisabled = true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment