Loading

缓存管理的帮助类(更新clear)

    public class DictionaryCacheManager<TK,TV>
    {
        private Dictionary<TK, TV> cacheDic = new Dictionary<TK,TV>();
        private Dictionary<TK, object> lockDic = new Dictionary<TK, object>();

        public TV Get(TK key,Func<TV> getValue)
        {
            if(!CheckKey(key))
            {
                CheckLock(key);
            }
            
            if(!CheckKey(key))
            {
                lock(lockDic[key])
                {
                    if(!CheckKey(key)||cacheDic[key]==null)
                    {
                        cacheDic[key] = getValue();
                    }
                }
            }
            return cacheDic[key];
        }

        private object _lock = new object();
        private void CheckLock(TK key)
        {
            lock(_lock)
            {
                if(!lockDic.ContainsKey(key))
                {
                    lockDic.Add(key, new object());
                }
            }
        }

        private bool CheckKey(TK key)
        {
            return cacheDic.ContainsKey(key);
        }

        public void Clear()
        {
            lock(_lock)
            {
                lockDic.Clear();
                cacheDic.Clear();
            }
        }
        public void Clear(TK key)
        {
            lock(lockDic[key])
            {
                cacheDic.Remove(key);
            }
        }
    }

 

很简单

posted @ 2012-04-20 22:46  today4king  阅读(460)  评论(2编辑  收藏  举报