【发布时间】:2013-06-02 09:46:10
【问题描述】:
我想使用应用程序缓存在我的 ASP.net 3.5 网站上创建一个应用程序范围的提要。我用来填充缓存的数据获取速度很慢,可能长达 10 秒(来自远程服务器的数据馈送)。我的问题/困惑是,构建缓存管理的最佳方式是什么。
private const string CacheKey = "MyCachedString";
private static string lockString = "";
public string GetCachedString()
{
string data = (string)Cache[CacheKey];
string newData = "";
if (data == null)
{
// A - Should this method call go here?
newData = SlowResourceMethod();
lock (lockString)
{
data = (string)Cache[CacheKey];
if (data != null)
{
return data;
}
// B - Or here, within the lock?
newData = SlowResourceMethod();
Cache[CacheKey] = data = newData;
}
}
return data;
}
实际的方法将由 HttpHandler (.ashx) 呈现。
如果我在“A”点收集数据,我会缩短锁定时间,但最终可能会多次调用外部资源(来自所有试图引用提要的网页)。如果我把它放在'B'点,锁定时间会很长,我认为这是一件坏事。
什么是最好的方法,或者我可以使用更好的模式吗?
任何建议将不胜感激。
【问题讨论】:
-
出于好奇,您为什么不使用像 memcached 或类似的预构建缓存解决方案? (stackoverflow.com/questions/3667433/…)
-
我根本没有遇到预建的缓存解决方案,但我会调查 - 谢谢。