ASP.net Cache Absolute Expiration not working

后端 未结 3 1551
渐次进展
渐次进展 2021-02-07 11:17

I am storing a single integer value in HttpContext.Cache with an absolute expiration time of 5 minutes from now. However, after waiting 6 minutes (or longer), the integer value

3条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-02-07 11:45

    It turns out that this line:

    HttpContext.Current.Cache[remoteIp] = ((int)HttpContext.Current.Cache[remoteIp]) + 1;
    

    removes the previous value and re-inserts the value with NO absolute or sliding expiration time. In order to get around this I had to create a helper class and use it like so:

    public class IncrementingCacheCounter
    {
        public int Count;
        public DateTime ExpireDate;
    }
    
    public void UpdateCountFor(string remoteIp)
    {
        IncrementingCacheCounter counter = null;
        if (HttpContext.Current.Cache[remoteIp] == null)
        {
            var expireDate = DateTime.Now.AddMinutes(5);
            counter = new IncrementingCacheCounter { Count = 1, ExpireDate = expireDate };
        }
        else
        {
            counter = (IncrementingCacheCounter)HttpContext.Current.Cache[remoteIp];
            counter.Count++;
        }
        HttpContext.Current.Cache.Insert(remoteIp, counter, null, counter.ExpireDate, Cache.NoSlidingExpiration, CacheItemPriority.Default, null);
    }
    

    This will get around the issue and let the counter properly expire at the absolute time while still enabling updates to it.

提交回复
热议问题