C# ASP.NET:当HttpContext.Current为空(为null)时如何访问缓存?

13

在 Global.aspx 中的 Application_End() 方法中,HttpContext.Current 为 null。但我仍然希望能够访问缓存 - 因为它在内存中,所以想知道是否可以以某种方式引用它以将位保存到磁盘。

问题 - 当 HttpContext.Current 为 null 时,有没有办法以某种方式引用内存中的缓存?

也许我可以创建一个全局静态变量,用来存储指向缓存的指针,并在 HTTP 请求中更新它 (伪代码: "static <pointer X>" = HttpRequest.Current) ,然后在 Application_End() 方法中通过该指针检索对缓存的引用?

在没有进行 Http 请求时,有更好的访问内存中的 Cache 的方法吗?

3个回答

31

11

我正在使用以下的 getter 方法来返回一个 System.Web.Caching.Cache 对象,目前它对我来说是有效的。

get
{
    return (System.Web.HttpContext.Current == null) 
        ? System.Web.HttpRuntime.Cache 
        : System.Web.HttpContext.Current.Cache;
}

这基本上支持了James Gaunt的观点,但当然只会帮助在应用程序结束时获取缓存。

编辑:我可能是从James链接到的Scott Hanselman博客的评论中得到这个观点的!


6

在 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
}

如果这种方法对您不适用,请告诉我。希望它能帮助您解决问题。最好的问候,Dima。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接