我正在HttpContext.Cache中存储一个整数值,绝对过期时间为5分钟.然而,等待6分钟(或更长时间)后,整数值仍然在缓存中(即使绝对过期已经过去也不会被清除).这是我正在使用的代码:
- public void UpdateCountFor(string remoteIp)
- {
- // only returns true the first time its run
- // after that the value is still in the Cache
- // even after the absolute expiration has passed
- // so after that this keeps returning false
- if (HttpContext.Current.Cache[remoteIp] == null)
- {
- // nothing for this ip in the cache so add the ip as a key with a value of 1
- var expireDate = DateTime.Now.AddMinutes(5);
- // I also tried:
- // var expireDate = DateTime.UtcNow.AddMinutes(5);
- // and that did not work either.
- HttpContext.Current.Cache.Insert(remoteIp,1,null,expireDate,Cache.NoSlidingExpiration,CacheItemPriority.Default,null);
- }
- else
- {
- // increment the existing value
- HttpContext.Current.Cache[remoteIp] = ((int)HttpContext.Current.Cache[remoteIp]) + 1;
- }
- }
我第一次运行UpdateCountFor(“127.0.0.1”)时,它将使用键“127.0.0.1”将1插入到缓存中,从预期的5分钟绝对到期.然后每个后续的运行都会增加缓存中的值.但是,等待10分钟后,它将继续增加缓存中的值.该值永远不会过期,从不会从缓存中删除.这是为什么?
这是我的理解,绝对过期时间意味着该项目将在当时被删除.我做错了吗?我误会了吗?
我期望在5分钟之后从Cache中删除该值,但是在重建项目之前,它将保留在该位置.
这一切都在本地机器上的.NET 4.0上运行.
解决方法
事实证明这一行:
- HttpContext.Current.Cache[remoteIp] = ((int)HttpContext.Current.Cache[remoteIp]) + 1;
删除以前的值,并重新插入值为无绝对或滑动过期时间.为了解决这个问题,我不得不创建一个帮助类并使用它:
- 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,counter.ExpireDate,null);
- }
这将解决问题,并让计数器在绝对时间正确到期,同时仍然允许更新.