Skip to content

Instantly share code, notes, and snippets.

@SangeetAgarwal
Created September 14, 2015 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SangeetAgarwal/b47fb949e9ab7a79bc21 to your computer and use it in GitHub Desktop.
Save SangeetAgarwal/b47fb949e9ab7a79bc21 to your computer and use it in GitHub Desktop.
public T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class
{
T item = MemoryCache.Default.Get(cacheKey) as T;
int duration;
if (ConfigurationManager.AppSettings["InMemoryCacheDuration"] == null ||
!Int32.TryParse(ConfigurationManager.AppSettings["InMemoryCacheDuration"], out duration))
duration = 30;
if (item != null) return item;
var slidingExpirationPolicy = new CacheItemPolicy()
{
SlidingExpiration = new TimeSpan(0, duration, 0)
};
item = getItemCallback();
MemoryCache.Default.Add(cacheKey, item, slidingExpirationPolicy);
return item;
}
}
interface ICacheService
{
T GetOrSet<T>(string cacheKey, Func<T> getItemCallback) where T : class;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment