c# - Application_End() 无法通过 HttpContext.Current.Cache[key] 访问缓存

标签 c# asp.net caching httpcontext.cache application-end

我希望能够在应用程序重新启动之间维护某些对象。

为此,我想在 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/

相关文章:

C#.net 如何通过代码将图像动态添加到表格单元格中

c# - 如何将 DataGridView 与 SqlDataReader 绑定(bind)

c# - Visual Studio 2008 中类似 "if statements"的垂直线?

c# - MVC 路由不适用于虚拟目录上的非默认/根操作 Controller

c# - 如何在 asp.net 中使用分页保留 gridview 中控件的状态?

python - freezeset 足以在 python 字典中缓存对称输入数据吗?

c# - 为什么允许使用 string.Substring(length,0)?

caching - 使用Guava进行高性能的线程安全缓存

performance - Oracle Coherence 缓存和应用服务器的 CPU 使用率

asp.net - 是否有任何高于帐户级别的 ASP.NET Identity 实现?