Skip to content

Instantly share code, notes, and snippets.

@leegould
Created March 2, 2015 10:55
Show Gist options
  • Save leegould/7ce7f233bc8cb59baef8 to your computer and use it in GitHub Desktop.
Save leegould/7ce7f233bc8cb59baef8 to your computer and use it in GitHub Desktop.
Memory Cache Extensions
/// <summary>
/// Extensions for memory cache.
/// </summary>
public static class MemoryCacheExtensions
{
/// <summary>
/// Add result to memory cache.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cache"></param>
/// <param name="fn"></param>
/// <param name="key"></param>
/// <param name="cacheExpiry"></param>
/// <param name="reloadcache"></param>
/// <returns></returns>
public static T MemCacheResult<T>(this MemoryCache cache, Func<T> fn, string key = "", DateTimeOffset? cacheExpiry = null, bool reloadcache = false) where T : class
{
try
{
var cacheName = typeof(T).Name + key;
var cacheContents = cache[cacheName] as T;
if (!reloadcache && cacheContents != null)
{
return cacheContents;
}
cacheContents = fn();
var cacheExpiryTime = cacheExpiry.HasValue ? cacheExpiry.Value : DateTimeOffset.Now.AddHours(12);
var policy = new CacheItemPolicy { AbsoluteExpiration = cacheExpiryTime };
cache.Set(cacheName, cacheContents, policy);
return cacheContents;
}
catch (Exception ex)
{
Logger.ErrorLog(string.Format("Memory cache error: {0}", ex));
return fn();
}
}
/// <summary>
/// Get all keys
/// </summary>
/// <param name="cache"></param>
/// <returns></returns>
/// <see cref="http://blog.aggregatedintelligence.com/2011/01/listing-contents-of-memorycache.html"/>
public static IList<string> GetMemCacheKeys(this MemoryCache cache)
{
try
{
var items = new List<string>();
IDictionaryEnumerator cacheEnumerator = (IDictionaryEnumerator)((IEnumerable)cache).GetEnumerator();
while(cacheEnumerator.MoveNext())
{
items.Add(cacheEnumerator.Key.ToString());
}
return items;
}
catch (Exception ex)
{
Logger.ErrorLog(string.Format("Memory cache error: {0}", ex));
return null;
}
}
/// <summary>
/// Clear with key and type.
/// </summary>
/// <param name="cache"></param>
/// <param name="key"></param>
/// <typeparam name="T"></typeparam>
public static void ClearMemCacheResult<T>(this MemoryCache cache, string key)
{
try
{
var cacheName = typeof(T).Name + key;
if (cache[cacheName] != null)
{
cache.Remove(cacheName);
}
}
catch (Exception ex)
{
Logger.ErrorLog(string.Format("Memory cache clearing error: {0}", ex));
}
}
/// <summary>
/// Clear with full key.
/// </summary>
/// <param name="cache"></param>
/// <param name="key"></param>
public static void ClearMemCacheResult(this MemoryCache cache, string key)
{
try
{
var cacheName = key;
if (cache[cacheName] != null)
{
cache.Remove(cacheName);
}
}
catch (Exception ex)
{
Logger.ErrorLog(string.Format("Memory cache clearing error: {0}", ex));
}
}
/// <summary>
/// Clear all items
/// </summary>
/// <param name="cache"></param>
/// <see cref="http://stackoverflow.com/questions/4183270/how-to-clear-the-net-4-memorycache"/>
public static void ClearMemCache(this MemoryCache cache)
{
List<KeyValuePair<String, Object>> cacheItems = (from n in cache.AsParallel() select n).ToList();
foreach (KeyValuePair<String, Object> a in cacheItems)
{
cache.Remove(a.Key);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment