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

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Date Time
8.Design Patterns
9.Development Class
10.Event
11.File Stream
12.Generics
13.GUI Windows Form
14.Internationalization I18N
15.Language Basics
16.LINQ
17.Network
18.Office
19.Reflection
20.Regular Expressions
21.Security
22.Services Event
23.Thread
24.Web Services
25.Windows
26.Windows Presentation Foundation
27.XML
28.XML LINQ
C# / C Sharp » Development Class » CacheScreenshots 
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[cacheKeynull;
        }

        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
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.