Tuesday, 21 August 2012

Generic class for caching in windows application for .Net Framework 3.5, 3.0 and 2.0


A generic class to cache data in in-momory cache for window application (Framework 3.5, 3.0, 2.0). Please refer the below code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Utils.Framework.Common
{
    /// <summary>
    /// Cache Utility class
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <remarks></remarks>
    public static class CacheUtils<T> where T : class
    {
        private static Dictionary<string, object> cachedHashSet = new Dictionary<string, object>();
        private static readonly object lockObject = new object();

        /// <summary>
        /// Sets the cache.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <param name="objValue">The obj value.</param>
        /// <remarks></remarks>
        public static void SetCache(string key, T objValue)
        {

            lock (lockObject)
            {
                //Delete cache if it exists already 
                if (cachedHashSet.ContainsKey(key))
                {
                    DeleteCache(key);
                    cachedHashSet.Add(key, objValue);
                }
                else
                {
                    cachedHashSet.Add(key, objValue);
                }
            }

        }

        /// <summary>
        /// Gets the cache from cache memory.
        /// </summary>
        /// <param name="key">The key.</param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static T GetCache(string key)
        {
            if (cachedHashSet.ContainsKey(key))
            {
                return cachedHashSet[key] as T;
            }
            return default(T);
        }

        /// <summary>
        /// Deleting cache.
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public static bool DeleteCache(string key)
        {
            if (cachedHashSet.ContainsKey(key))
            {
                cachedHashSet.Remove(key);
            }
            return true;

        }
    }
}

No comments:

Post a Comment