Created
December 1, 2014 00:50
-
-
Save lukencode/614bf815c7edcbfea3e8 to your computer and use it in GitHub Desktop.
CacheExtensions
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 | |
{ | |
static object sync = new object(); | |
/// <summary> | |
/// Executes a method and stores the result in cache using the given cache key. If the data already exists in cache, it returns the data | |
/// and doesn't execute the method. Thread safe, although the method parameter isn't guaranteed to be thread safe. | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="cache"></param> | |
/// <param name="cacheKey">Each method has it's own isolated set of cache items, so cacheKeys won't overlap accross methods.</param> | |
/// <param name="method"></param> | |
/// <param name="expirationSeconds">Lifetime of cache items, in seconds</param> | |
/// <returns></returns> | |
public static T Data<T>(this Cache cache, string cacheKey, TimeSpan expiration, Func<T> method) | |
{ | |
var data = (T)cache[cacheKey]; | |
if (data == null) | |
{ | |
data = method(); | |
if (expiration != null && data != null) | |
lock (sync) | |
{ | |
cache.Insert(cacheKey, data, null, DateTime.Now + expiration, Cache.NoSlidingExpiration); | |
} | |
} | |
return data; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment