Skip to content

Instantly share code, notes, and snippets.

@mikezhuyuan
Created August 27, 2012 06:49
Show Gist options
  • Save mikezhuyuan/3486324 to your computer and use it in GitHub Desktop.
Save mikezhuyuan/3486324 to your computer and use it in GitHub Desktop.
public class MemoryCache : IObjectCache
{
public T Get<T>(CacheKey key, DateTime absoluteExpiration, Func<T> load)
{
var policy = new System.Runtime.Caching.CacheItemPolicy();
policy.AbsoluteExpiration = absoluteExpiration;
return Get(key, policy, load);
}
public T Get<T>(CacheKey key, TimeSpan slidingExpiration, Func<T> load)
{
var policy = new System.Runtime.Caching.CacheItemPolicy();
policy.SlidingExpiration = slidingExpiration;
return Get(key, policy, load);
}
private T Get<T>(CacheKey key, System.Runtime.Caching.CacheItemPolicy policy, Func<T> load)
{
var keyStr = key.ToString();
var cache = System.Runtime.Caching.MemoryCache.Default;
T result = (T)cache[keyStr];
if (result == null)
{
result = load();
cache.Add(new System.Runtime.Caching.CacheItem(keyStr, result), policy);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment