views:

152

answers:

2

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

It seems that the Trace statement only runs once, and not every 30 seconds after the Cache item has expired. The only way I can get it to refresh the Cached item is to make a code chance and rebuild the project, which is obviously less than ideal.

What am I missing? Thanks in advance...

A: 

I had this problem before and asked a question here; it was never really answered, but there might be some helpful debugging tips in the answers.

Mark B
+3  A: 

The set part of the property is probably the cause - Cache["key"] = value is equivalent to calling Cache.Insert with 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); 
    }
}
Pent Ploompuu
That makes sense. That said, what's the best way to update the cached item?
ianpoley
I added the modified code for the property that should work as intended.
Pent Ploompuu
Bingo! Thanks so much, that worked like a charm.
ianpoley