我希望能够在应用程序重新启动之间维护某些对象。
为此,我想在 Global.asax Application_End()
函数中将特定的缓存项写入磁盘,然后在 Application_Start()
中重新加载它们。
我目前有一个缓存助手类,它使用以下方法返回缓存值:
return HttpContext.Current.Cache[key];
问题:在Application_End()
期间,HttpContext.Current
为空,因为没有网络请求(这是一个自动清理程序)-因此,我无法访问 .Cache[]
来检索要保存到磁盘的任何项目。
问题:如何在Application_End()
期间访问缓存项?
最佳答案
如果你想在它被释放之前访问缓存对象,你需要使用像这样的方法将对象添加到缓存:
将命名空间 System.Web.Caching 导入您的应用程序,您在其中使用将对象添加到缓存。
//Add callback method to delegate
var onRemove = new CacheItemRemovedCallback(RemovedCallback);
//Insert object to cache
HttpContext.Current.Cache.Insert("YourKey", YourValue, null, DateTime.Now.AddHours(12), Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, onRemove);
当这个对象要被释放时会调用下面的方法:
private void RemovedCallback(string key, object value, CacheItemRemovedReason reason)
{
//Use your logic here
//After this method cache object will be disposed
}
关于c# - Application_End() 无法通过 HttpContext.Current.Cache[key] 访问缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4419981/