Created
February 2, 2013 12:03
-
-
Save marisks/4697018 to your computer and use it in GitHub Desktop.
Static class to simplify work with ASP.NET Cache.
This file contains hidden or 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 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