2010-12-15 73 views
9

在Global.aspx中的Application_End()期間,HttpContext.Current爲空。我仍然希望能夠訪問緩存 - 它在內存,所以想看看我是否可以參考它以某種方式將位保存到磁盤。C#ASP.NET:如何訪問緩存時沒有HttpContext.Current可用(爲空)?

問題 - 有沒有辦法在HttpContext.Current爲空時以某種方式引用內存中的緩存?

也許我可以創建一個全局靜態變量來存儲指向緩存的指針,我可以在HTTP請求上更新(僞:"static <pointer X>" = HttpRequest.Current)並通過Application_End()中的指針檢索緩存的引用?

有沒有更好的方式來訪問內存中的緩存,當沒有Http請求時?

回答

4

在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

我正在使用下面的getter來返回一個System.Web.Caching.Cache對象,它正在爲我工​​作。

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

這基本上支持詹姆斯·岡特,但當然只是幫助在應用程序結束緩存。

編輯:我可能從Scott Hanselman博客James的一篇評論中得到了這個鏈接!