Skip to content

Instantly share code, notes, and snippets.

@MetaRecursion
Forked from kevinblake/ICacheService.cs
Last active December 23, 2015 12:09
Show Gist options
  • Save MetaRecursion/6633236 to your computer and use it in GitHub Desktop.
Save MetaRecursion/6633236 to your computer and use it in GitHub Desktop.
Updated ASP.NET caching sample with thread-safety.
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;
}
}
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;
}
}
}
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