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);
}
}
}
|
很简单
本文转自today4king博客园博客,原文链接:http://www.cnblogs.com/jinzhao/archive/2012/04/20/2460652.html,如需转载请自行联系原作者