ASP.net Cache Absolute Expiration not working

后端 未结 3 1550
渐次进展
渐次进展 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:51

    There's a simpler answer than what smoak posted. Using that example as a starting point, the updated code below works and doesn't require a re-insert. The reason this works is because classes are reference types. Thus, when you update the counter inside the class instance it doesn't cause the cache to trigger an update.

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

提交回复
热议问题