-
-
Save MetaRecursion/6633236 to your computer and use it in GitHub Desktop.
Updated ASP.NET caching sample with thread-safety.
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
using System; | |
namespace AppNamespace.Caching | |
{ | |
interface ICacheService | |
{ | |
T Get<T>(string cacheKey, Func<T> getItemCallback) where T : class; | |
T Get<T>(string cacheKey, DateTime absoluteExpiration, TimeSpan slidingExpiration, Func<T> getItemCallback) where T : class; | |
} | |
} |
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
using System; | |
using System.Web; | |
using System.Web.Caching; | |
namespace AppNamespace.Caching | |
{ | |
public class WebMemoryCache : ICacheService | |
{ | |
private static readonly object WebCacheLock = new object(); | |
public T Get<T>(string cacheKey, Func<T> getItemCallback) where T : class | |
{ | |
return Get(cacheKey, System.Web.Caching.Cache.NoAbsoluteExpiration, TimeSpan.FromHours(1), getItemCallback); | |
} | |
public T Get<T>(string cacheKey, DateTime absoluteExpiration, TimeSpan slidingExpiration, Func<T> getItemCallback) where T : class | |
{ | |
// Return cached value if exists | |
var item = HttpRuntime.Cache.Get(cacheKey) as T; | |
if (item != null) | |
return item; | |
// Double-checked locking | |
// See: http://stackoverflow.com/questions/39112/what-is-the-best-way-to-lock-cache-in-asp-net | |
lock (WebCacheLock) | |
{ | |
// Ensure cache wasn't updated while waiting for lock | |
// Return cached value if exists | |
item = HttpRuntime.Cache.Get(cacheKey) as T; | |
if (item != null) | |
return item; | |
// Generate item | |
item = getItemCallback(); | |
// Ensure item is not null | |
// Could potentially just return null here, but callers may expect cache to prevent | |
// multiple getItemCallback invocations. | |
if (item == null) | |
throw new ArgumentException("Item creation function yielded null, which is not cacheable.", "getItemCallback"); | |
// Add item to cache | |
HttpContext.Current.Cache.Insert(cacheKey, item, null, absoluteExpiration, slidingExpiration); | |
} | |
return item; | |
} | |
} | |
} |
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
var cachedTime = new WebMemoryCache().Get("CachedDateTimeKey", Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(5), () => | |
{ | |
return DateTime.UtcNow; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment