ASP.net缓存绝对到期不工作
发布时间:2020-12-15 23:21:56 所属栏目:asp.Net 来源:网络整理
导读:我正在HttpContext.Cache中存储一个整数值,绝对过期时间为5分钟.然而,等待6分钟(或更长时间)后,整数值仍然在缓存中(即使绝对过期已经过去也不会被清除).这是我正在使用的代码: public void UpdateCountFor(string remoteIp){ // only returns true the firs
我正在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); } 这将解决问题,并让计数器在绝对时间正确到期,同时仍然允许更新. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – MVC3在编辑时,十进制截断为2位小数
- 如何将我的模型数据(列表)映射到另一个viewmodel数据(列表)
- asp.net – 如何以编程方式覆盖web.config设置
- ASP.NET – jQuery ajax调用队列而不是并发运行?
- asp.net-mvc-3 – MVC中的SSO(单点登录)
- asp.net-mvc – 在使用Asp.Net MVC ActionLink,RedirectToA
- ASP.NET:jQuery AJAX’data’param问题
- asp.net-mvc – 具有引导Navbar的MVC – 将所选项目设置为活
- asp.net – 触发OWIN cookie中间件设置为被动身份验证模式的
- asp.net-mvc – System.Data.SqlClient.SqlException:无效
推荐文章
站长推荐
- asp.net-mvc – 区域在ASP.NET视图?
- asp.net – Visual studio – 在浏览器中查看时使
- 为ASP.Net AJAX String.format方法创建TypeScrip
- SignalR控制台自托管服务端向web客户端指定用户推
- ASP.NET MVC删除操作方法中的查询字符串
- asp.net – 具有主动/主动粘滞会话的SignalR和负
- asp.net – LinkBut??ton CommandName和CommandA
- asp.net 文章内容分页显示的代码
- asp.net-mvc – 我如何编写一个ActionFilter来确
- asp.net-mvc – 如何从asp.net MVC 4应用程序中的
热点阅读