Cached Item Never Expires

I have a class that contains the following property:

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

The Trace statement seems to work only once, and not every 30 seconds after the expiration of the Cache element. The only way I can update the Cached element is to make the code probable and rebuild the project, which is obviously not perfect.

What am I missing? Thanks in advance...

+5
source share
2 answers

Part of the property setis probably the reason - Cache["key"] = valueequivalent to calling Cache.Insertc NoAbsoluteExpiration, NoSlidingExpiration, which means it never expires. The correct solution would look like this:

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); 
    }
}
+8
source

; , .

0

All Articles