我有一个包含以下属性的类:
public Dictionary<string, int> CommentCounts {
get {
string cacheKey = "CommentCounts";
HttpContext c = HttpContext.Current;
if (c.Cache[cacheKey] == null) {
c.Cache.Insert(cacheKey, new Dictionary<string, int>(), null, DateTime.UtcNow.AddSeconds(30), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.High, null);
c.Trace.Warn("New cached item: " + cacheKey);
}
return (Dictionary<string, int>)c.Cache[cacheKey];
}
set {
HttpContext.Current.Cache["CommentCounts"] = value;
}
}
似乎Trace语句只运行一次,而不是在Cache项目到期后每30秒运行一次。我可以让它刷新缓存项的唯一方法是创建代码机会并重建项目,这显然不太理想。
我错过了什么?提前谢谢......
答案 0 :(得分:8)
该属性的set
部分可能是原因 - Cache["key"] = value
相当于使用Cache.Insert
调用NoAbsoluteExpiration, NoSlidingExpiration
,这意味着它永不过期。正确的解决方案如下所示:
public Dictionary<string, int> CommentCounts {
get {
const string cacheKey = "CommentCounts";
HttpContext c = HttpContext.Current;
if (c.Cache[cacheKey] == null) CommentCounts = new Dictionary<string, int>();
return (Dictionary<string, int>)c.Cache[cacheKey];
}
set {
const string cacheKey = "CommentCounts";
c.Cache.Insert(cacheKey, value, null, DateTime.UtcNow.AddSeconds(30), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.High, null);
c.Trace.Warn("New cached item: " + cacheKey);
}
}
答案 1 :(得分:0)
我之前遇到过这个问题asked a question here;它从来没有真正回答过,但答案中可能会有一些有用的调试技巧。