Skip to content

Instantly share code, notes, and snippets.

@jaguire
Last active February 9, 2016 19:46
Show Gist options
  • Save jaguire/5158046 to your computer and use it in GitHub Desktop.
Save jaguire/5158046 to your computer and use it in GitHub Desktop.
Cache the output of a method call.
public static class CacheExtensions
{
private static readonly object ThisLock = new object();
public static T Get<T>(this Cache cache, string key, Func<T> builder, DateTime expiration)
{
var data = cache.Get(key);
if (data == null)
{
lock (ThisLock)
{
data = cache.Get(key);
if (data == null)
{
data = builder.Invoke();
cache.Add(key, data, null, expiration, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
}
}
}
return (T)data;
}
}
var cache = new Cache();
var value = cache.Get("MyKey", () => GetFooById(42), DateTime.Now.AddHours(3));
// The method to cache results from.
private string GetFooById(int id)
{ /* ... */ }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment