Have you ever created a new email message with the main objective being to send someone an attachment and then forget to attach said attachment? Apparently I did something similar to that in my last post. At the time of the post, I couldn't get the attach file method to work so I intended to add it later, but I didn't. That makes me a sad panda :(
I've been using a variant of this caching method with good results for quite some time. So to make amends I'm going to post an updated version AND a proper sample solution. And this time, I will remember to attach it.
using System;
using System.Reflection;
using System.Web;
using System.Web.Caching;
using log4net;
namespace BDI.Caching
{
public class CacheHelper
{
private static readonly ILog log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType );
private static readonly bool isInfoEnabled = log.IsInfoEnabled;
private static readonly Cache cache = HttpRuntime.Cache;
private CacheHelper() {}
public static T GetFromCache<T>(
string key,
int cacheTimeInMinutes,
CacheExpiration cacheExpiration,
Func<T> retrieveMethod ) where T : class
{
var target = cache[key] as T;
if ( target == null )
{
if (isInfoEnabled)
log.Info("Cache miss for key:" + key + " type:" + typeof (T));
target = retrieveMethod();
var absoluteExpiration = Cache.NoAbsoluteExpiration;
var slidingExpiration = Cache.NoSlidingExpiration;
switch (cacheExpiration)
{
case CacheExpiration.Sliding:
slidingExpiration = new TimeSpan(0, cacheTimeInMinutes, 0);
break;
case CacheExpiration.Absolute:
absoluteExpiration = DateTime.Now.AddMinutes(cacheTimeInMinutes);
break;
}
cache.Insert(key, target, null, absoluteExpiration,
slidingExpiration, CacheItemPriority.Normal, OnRemove);
}
else
{
if ( isInfoEnabled )
log.Info( "Cache hit for key:" + key + " type:" + typeof( T ) );
}
return target;
}
public static void OnRemove( string key, object cacheItem, CacheItemRemovedReason reason )
{
if( isInfoEnabled )
log.Info( "Object removed from cache: Key-" + key + ": Reason-" + reason );
}
public static void RemoveFromCache( string key )
{
if( isInfoEnabled )
log.Info( "Object manually removed from cache: Key-" + key );
cache.Remove( key );
}
}
}
Posted
03-31-2009 9:38 PM
by
anortham