【发布时间】:2011-08-19 14:58:28
【问题描述】:
我在 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") 时,它将 1 插入到缓存中,键为“127.0.0.1”,并且从现在开始的绝对到期时间为 5 分钟,正如预期的那样。然后每次后续运行都会增加缓存中的值。但是,在等待 10 分钟后,它会继续增加 Cache 中的值。该值永不过期,也永远不会从缓存中删除。这是为什么呢?
据我了解,绝对过期时间意味着该项目大约会在那个时候被删除。难道我做错了什么?我是不是误会了什么?
我预计该值会在 5 分钟后从缓存中删除,但它会一直保留在那里,直到我重建项目。
这一切都在我本地机器上的 .NET 4.0 上运行。
【问题讨论】:
-
你的 web.config 中有什么奇怪的缓存配置设置吗?
-
不,我有默认的 web.config
标签: asp.net caching asp.net-mvc-3 c#-4.0