缓存项目永不过期

ian*_*ley 5 c# asp.net caching

我有一个包含以下属性的类:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

似乎Trace语句只运行一次,而不是在Cache项目到期后每30秒运行一次.我可以让它刷新缓存项的唯一方法是创建代码机会并重建项目,这显然不太理想.

我错过了什么?提前致谢...

Pen*_*puu 8

set部分财产可能是原因- Cache["key"] = value等同于调用Cache.InsertNoAbsoluteExpiration, 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); 
    }
}
Run Code Online (Sandbox Code Playgroud)