Last active
February 9, 2016 19:46
-
-
Save jaguire/5158046 to your computer and use it in GitHub Desktop.
Cache the output of a method call.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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