首页 文章

C#ASP.NET:当没有HttpContext.Current可用时,如何访问缓存(为空)?

提问于
浏览
11

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

Question - 当HttpContext.Current为空时,有没有办法以某种方式在内存中引用缓存?

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

当没有Http请求时,是否有更好的方法来访问内存中的Cache?

3 回答

  • 25

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

    如果这种方法不适合您,请告诉我 . 希望它能帮助你解决问题 .

    最好的问候,迪马 .

  • 9

    您应该可以通过HttpRuntime.Cache访问它

    http://www.hanselman.com/blog/UsingTheASPNETCacheOutsideOfASPNET.aspx

    根据Scott的说法 - 看看Reflector HttpContext.Current.Cache只是调用HttpRuntime.Cache - 所以你也可以这样总是访问它 .

  • 4

    我正在使用以下getter返回一个对我有用的System.Web.Caching.Cache对象 .

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

    这基本上支持James Gaunt,但当然只是帮助在Application End中获取缓存 .

    编辑:我可能从詹姆斯链接到斯科特汉塞尔曼博客的评论之一得到了这个!

相关问题