Skip to content

Instantly share code, notes, and snippets.

@michaelbramwell
Created March 31, 2016 03:13
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/c545ac6527b7be145e046fa2117e2736 to your computer and use it in GitHub Desktop.
Save michaelbramwell/c545ac6527b7be145e046fa2117e2736 to your computer and use it in GitHub Desktop.
Generic get/set operation for types that are stored in the <see cref="MemoryCache"/>
public static T GetFromMemoryCache<T>(string key, int cacheTime, Func<T> whenKeyNotFound)
{
var items = MemoryCache.Default;
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
items.Add(key, item, DateTime.Now.AddMinutes(cacheTime));
return item;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment