Skip to content

Instantly share code, notes, and snippets.

@dampee
Last active December 31, 2015 17:29
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 dampee/8020523 to your computer and use it in GitHub Desktop.
Save dampee/8020523 to your computer and use it in GitHub Desktop.
Generic http cache with locking
using System;
using System.Web;
using System.Web.Caching;
using Umbraco.Core.Logging;
/// <summary>
/// Generic cache class
/// </summary>
/// <typeparam name="T">The type of the object to be cached</typeparam>
/// <remarks>
/// if the "getFunction" returns null, nothing can be cached and the "getFunction" will
/// be called every time the object is needed
/// original from http://tompi.github.io/2012/04/02/Generic-ASP.NET-Cache-pattern
/// </remarks>
/// <example>
/// var myobj = mycache.Get(padLock, strCacheName, () =>
/// {
/// return GetObject() ?? new MyObject();
/// }, 60 * 5);
/// </example>
public class Cache<T> where T : class
{
public T Get(object lockObject, string key, Func<T> getFunction, int secondsToCache)
{
var result = HttpRuntime.Cache.Get(key);
if (result == null)
{
lock (lockObject)
{
result = HttpRuntime.Cache.Get(key);
if (result == null)
{
result = getFunction();
if (result == null) return null;
HttpRuntime.Cache.Insert(key, result, null, DateTime.UtcNow.AddSeconds(secondsToCache), Cache.NoSlidingExpiration);
// do some umbraco logging
LogHelper.Debug<Cache<T>>("Inserted object in cache: {0}", () => key);
}
}
}
return (T)result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment