缓存管理的帮助类(更新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); } } }
很简单