Skip to content

Instantly share code, notes, and snippets.

@marisks
Created February 2, 2013 12:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marisks/4697018 to your computer and use it in GitHub Desktop.
Save marisks/4697018 to your computer and use it in GitHub Desktop.
Static class to simplify work with ASP.NET Cache.
public static class CacheHelper
{
/// <summary>
/// Returns cache value or default(T) if no value in cache
/// </summary>
/// <typeparam name="T">Type of cached value</typeparam>
/// <param name="key">Cache key for cached value</param>
/// <returns>Cached value</returns>
public static T Get<T>(string key)
{
var value = default(T);
if (Exists(key))
{
value = (T)HttpRuntime.Cache[key];
}
return value;
}
/// <summary>
/// Returns value from cache if it exists in cache by provided key.
/// Returns value created by creator and adds this value to cache if value doesn't exist in cache by provided key.
/// </summary>
/// <typeparam name="T">Type of value to cache</typeparam>
/// <param name="key">Unique cache key for cacheable value</param>
/// <param name="creator">Function which creates value for caching</param>
/// <param name="cacheAdder">Action which adds value to cache</param>
/// <returns>Cached value</returns>
public static T GetOrCacheValue<T>(string key, Func<T> creator, Action<string, object> cacheAdder)
{
var value = Get<T>(key);
if (EqualityComparer<T>.Default.Equals(value, default(T)))
{
var lockObject = lockObjects.GetOrAdd(key, new object());
lock (lockObject)
{
value = Get<T>(key);
if (EqualityComparer<T>.Default.Equals(value, default(T)))
{
value = creator();
cacheAdder(key, value);
}
}
}
return value;
}
private static readonly ConcurrentDictionary<string, object> lockObjects = new ConcurrentDictionary<string, object>();
/// <summary>
/// Check for item in cache
/// </summary>
/// <param name="key">Name of cached item</param>
/// <returns></returns>
public static bool Exists(string key)
{
return HttpRuntime.Cache[key] != null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment