Memory Cache Lock : Cache « Development Class « C# / C Sharp






Memory Cache Lock

        
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Mvc30WebRole1.Util
{
    public class CacheUtility
    {
        private static Dictionary<string, object> MemCache = new Dictionary<string, object>();
        private static Dictionary<string, object> MemCacheLocks = new Dictionary<string, object>();
        private static List<string> keyNames = new List<string>() { "AllLocations" };

        static CacheUtility()
        {
            foreach (string item in keyNames)
            {
                MemCache.Add(item, null);
                MemCacheLocks.Add(item, new object());
            }
        }

        public static T GetFromCacheOrAdd<T>(string cacheKey, Func<object> populateMethod)
        {
            if (MemCache[cacheKey] == null)
            {
                lock (MemCacheLocks[cacheKey])
                {
                    if (MemCache[cacheKey] == null)
                    {
                        MemCache[cacheKey] = populateMethod.Invoke();
                    }
                }
            }

            object cachedItem = MemCache[cacheKey];

            if (cachedItem == null)
                throw new Exception("Unable to retrieve item from cache with cacheKey '" + cacheKey + "'");

            return (T)cachedItem;
        }

        public static void RemoveCacheItem(string cacheKey)
        {
            MemCache[cacheKey] = null;
        }

        public static void RemoveAllFromCache()
        {
            foreach (string item in keyNames)
            {
                RemoveCacheItem(item);
            }
        }
    }
}

   
    
    
    
    
    
    
    
  








Related examples in the same category

1.Provides efficient storage for cached items.
2.Provide a memory caching mechanism to save and retrieve results based on the associated key names