我想要使用 .NET
的 Lazy<T>
类来实现线程安全的缓存。假设我们有以下设置:
class Foo
{
Lazy<string> cachedAttribute;
Foo()
{
invalidateCache();
}
string initCache()
{
string returnVal = "";
//CALCULATE RETURNVAL HERE
return returnVal;
}
public String CachedAttr
{
get
{
return cachedAttribute.Value;
}
}
void invalidateCache()
{
cachedAttribute = new Lazy<string>(initCache, true);
}
}
我的问题:
- 这个方案会起作用吗?
- 锁定应该如何工作?
我觉得在invalidateCache附近缺少了一个锁,但是怎么也想不出来。
我确定这里肯定有问题,只是我还没找到哪里出了问题。
[编辑]
好吧,看起来我是对的,我还有一些事情没有考虑到。如果一个线程看到过时的缓存,那就非常糟糕了,所以“懒惰”方式不够安全。然而,这个属性访问次数非常频繁,所以我希望进行过早的优化,以便学习一些东西,并且拥有一个可用于线程安全缓存的模式。我会继续努力解决。
P.S.:我决定使对象线程不安全,并仔细控制对对象的访问。