代码之家  ›  专栏  ›  技术社区  ›  ianpoley

缓存项永不过期

  •  5
  • ianpoley  · 技术社区  · 15 年前

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

    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语句只运行一次,而不是在缓存项过期后每30秒运行一次。我唯一能让它刷新缓存项的方法是利用代码机会并重建项目,这显然不太理想。

    我错过了什么?事先谢谢…

    2 回复  |  直到 15 年前
        1
  •  8
  •   Pent Ploompuu    15 年前

    这个 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); 
        }
    }
    
        2
  •  0
  •   Community Mohan Dere    8 年前

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