【问题标题】:Cached item never expiring缓存项目永不过期
【发布时间】:2010-01-22 23:18:43
【问题描述】:

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

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 秒运行一次。我可以让它刷新缓存项的唯一方法是创造一个代码机会并重建项目,这显然不太理想。

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

【问题讨论】:

    标签: c# asp.net caching


    【解决方案1】:

    属性的set 部分可能是原因-Cache["key"] = value 相当于用NoAbsoluteExpiration, NoSlidingExpiration 调用Cache.Insert,这意味着它永远不会过期。正确的解决方案如下所示:

    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); 
        }
    }
    

    【讨论】:

    • 这是有道理的。也就是说,更新缓存项目的最佳方法是什么?
    • 我为应该按预期工作的属性添加了修改后的代码。
    【解决方案2】:

    我之前遇到过这个问题,asked a question here;它从未真正得到回答,但答案中可能有一些有用的调试技巧。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-15
      • 1970-01-01
      • 2012-08-14
      • 1970-01-01
      • 2011-03-31
      • 2011-10-16
      • 1970-01-01
      相关资源
      最近更新 更多