Skip to content

Instantly share code, notes, and snippets.

@michaelbramwell
Created March 9, 2016 01:24
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 michaelbramwell/90812be750a7d0218854 to your computer and use it in GitHub Desktop.
Save michaelbramwell/90812be750a7d0218854 to your computer and use it in GitHub Desktop.
Generic get/set operation for types that are stored in the <see cref="HttpContext.Cache"/>
public static T GetFromHttpCache<T>(string key, Cache items, int cacheTime, Func<T> whenKeyNotFound, CacheItemRemovedCallback onRemoveCallback = null)
{
if (items[key] != null)
{
// return from cache
return (T)items[key];
}
// return new item from caller and add to cache
var item = whenKeyNotFound();
//add to cache
if(onRemoveCallback == null)
{
items.Insert(key, item, null, DateTime.Now.AddMinutes(cacheTime), Cache.NoSlidingExpiration);
}
else
{
items.Insert(key, item, null, DateTime.Now.AddMinutes(cacheTime), Cache.NoSlidingExpiration, CacheItemPriority.Default, onRemoveCallback);
}
return item;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment