Application_End() 无法通过 HttpContext.Current.Cache[key] 访问缓存
我希望能够在应用程序重新启动之间维护某些对象。
为此,我想在 Global.asax Application_End()
函数中将特定的缓存项写入磁盘,并在 Application_Start()
上重新加载它们。
我目前有一个缓存助手类,它使用以下方法返回缓存的值:
return HttpContext.Current.Cache[key];
问题:在Application_End()
期间,HttpContext.Current
为 null,因为没有 Web 请求(这是一个自动清理过程) - 因此,我无法访问 .Cache[]
来检索任何要保存到磁盘的项目。
问题:如何在 Application_End()
期间访问缓存项?
I want to be able to maintain certain objects between application restarts.
To do that, I want to write specific cached items out to disk in Global.asax Application_End()
function and re-load them back on Application_Start()
.
I currently have a cache helper class, which uses the following method to return the cached value:
return HttpContext.Current.Cache[key];
Problem: during Application_End()
, HttpContext.Current
is null since there is no web request (it's an automated cleanup procedure) - therefore, I cannot access .Cache[]
to retrieve any of the items to save to disk.
Question: how can I access the cache items during Application_End()
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
作为替代解决方案,您可以将数据存储在应用程序对象(应用程序[key])中,或者简单地创建一个
静态类
并使用它来将数据保存在应用程序中 - 在这种情况下,数据仍然可用在Application_End 时。As an alternative solution you could store the data in Application object (Application[key]) or simply create a
static class
and use it to keep your data within app - in this case the data would sill be available upon Application_End.如果您想在缓存对象被释放之前访问它,您需要使用类似这样的方式将对象添加到缓存:
将命名空间 System.Web.Caching 导入到您正在使用添加对象到缓存的应用程序。
当要释放该对象时,将调用以下方法:
If you want to get access to cache object before it will be disposed, you need to use somethink like this to add object to cache:
Import namespace System.Web.Caching to your application where you are using adding objects to cache.
And when this object is going to be disposed will be called following method:
我强烈敦促您重新考虑您的方法。您可能想描述您想要做什么的具体细节,以便我们可以帮助您。
但是,如果您完全确定了它,那么您可以在实际设置值时将它们保存在磁盘上,即您的帮助器类将如下所示:
I strongly urge you to rethink your approach. You may want to describe specifics of what are you trying to do, so we might help you with that.
But if you are totally set on it, then you can simply save values on disk when you actually set them, i.e. your helper class would looks something like this:
当没有可用的 HttpContext 时,可以通过 HttpRuntime.Cache 访问缓存。然而,在Application_End,我相信缓存已经被刷新。
Dima Shmidt 概述的解决方案将是存储缓存值的最佳方法。也就是说,通过 CacheItemRemovedCallback 将项目添加到缓存,并将值存储到磁盘中。
You can access the cache through HttpRuntime.Cache when you don't have an HttpContext available. However, at Application_End, i believe the cache is already flushed.
The solution Dima Shmidt outlines would be the best approach to store your cached values. That is by adding your items to cache with a CacheItemRemovedCallback, and store the values to disk there.