Skip to content

Instantly share code, notes, and snippets.

@lukencode
Created December 9, 2011 00:46
Show Gist options
  • Save lukencode/1449524 to your computer and use it in GitHub Desktop.
Save lukencode/1449524 to your computer and use it in GitHub Desktop.
CacheExtensions
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 parametersn'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, int expirationSeconds, Func<T> method)
{
//var hash = method.GetHashCode().ToString();
//var data = (T)cache[hash + cacheKey];
cacheKey = cacheKey.ToLower();
var data = (T)cache[cacheKey];
if (data == null)
{
data = method();
if (expirationSeconds > 0 && data != null)
lock (sync)
{
//cache.Insert(hash + cacheKey, data, null, DateTime.Now.AddSeconds(expirationSeconds), Cache.NoSlidingExpiration);
cache.Insert(cacheKey, data, null, DateTime.Now.AddSeconds(expirationSeconds), Cache.NoSlidingExpiration);
}
}
return data;
}
public static void Clear(this Cache cache)
{
List<string> keys = new List<string>();
// retrieve application Cache enumerator
IDictionaryEnumerator enumerator = cache.GetEnumerator();
// copy all keys that currently exist in Cache
while (enumerator.MoveNext())
{
keys.Add(enumerator.Key.ToString());
}
// delete every key from cache
for (int i = 0; i < keys.Count; i++)
{
cache.Remove(keys[i]);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment