Last active
December 31, 2015 17:29
-
-
Save dampee/8020523 to your computer and use it in GitHub Desktop.
Generic http cache with locking
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
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