Wednesday, 22 August 2012

Generic class for caching in windows application for .Net Framework 4.0


Let’s write a generic class to cache data in in-memory cache for window application (Framework 4.0). Please refer the below code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Caching;
using System.IO;
namespace GenericUtils
{
    public static class CacheUtils<T> where T : class
    {
        private static ObjectCache cache = MemoryCache.Default;
        public static void SetCache(string key, T objValue)
        {
            //CacheItemPolicy policy = new CacheItemPolicy();
            //policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(2));
            //cache.Add(key, obj, policy);
            lock (typeof(CacheUtils<T>))
            {
                cache[key] = objValue;
            }
        }
        public static T GetCache(string key)
        {
            if (cache.Contains(key))
            {
                return (T)cache.Get(key);
            }
            return null;
        }
    }
}

No comments:

Post a Comment