Home > C# > C# CacheHelper

C# CacheHelper

December 19th, 2011 Leave a comment Go to comments

Just a simple class I put together for easy cache handling.

public class CacheHelper
{
    private static readonly ILog logger = LogManager.GetLogger(typeof(CacheHelper));
 
    public static T CachedResult<T>(string key, Func<T> valueRetrieval, double timeout = 5)
    {
        T result = (T)HttpContext.Current.Cache[key];
        if (result == null)
        {
            logger.InfoFormat("Cached item with key: {0} not found in Cache, fetching value", key);
 
            result = valueRetrieval.Invoke();
 
            HttpContext.Current.Cache.Insert(key, result, null, DateTime.Now.AddMinutes(timeout), Cache.NoSlidingExpiration);
        }
        else
        {
            logger.DebugFormat("Cached item with key: {0} retrieved from Cache", key);
        }
 
        return result;
    }
}

Usage example:

RssFeed rssFeed = CacheHelper.CachedResult<RssFeed>(url, () => TwitterApplication.GetPublicTimelineFeed(url));
Categories: C# Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Time limit is exhausted. Please reload CAPTCHA.