开发者

Application_End() cannot access cache through HttpContext.Current.Cache[key]

I want to be able to maintain certain objects between application restarts.

To do that, I want to write specific cached items out to disk in Global.asax Application_End() function and re-load them back on Application_Start().

I currently have a cache helper class, which us开发者_如何转开发es the following method to return the cached value:

return HttpContext.Current.Cache[key];

Problem: during Application_End(), HttpContext.Current is null since there is no web request (it's an automated cleanup procedure) - therefore, I cannot access .Cache[] to retrieve any of the items to save to disk.

Question: how can I access the cache items during Application_End()?


If you want to get access to cache object before it will be disposed, you need to use somethink like this to add object to cache:

Import namespace System.Web.Caching to your application where you are using adding objects to cache.

//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);

And when this object is going to be disposed will be called following method:

private void RemovedCallback(string key, object value, CacheItemRemovedReason reason)
{
    //Use your logic here

    //After this method cache object will be disposed
}


I strongly urge you to rethink your approach. You may want to describe specifics of what are you trying to do, so we might help you with that. But if you are totally set on it, then you can simply save values on disk when you actually set them, i.e. your helper class would looks something like this:

public static class CacheHelper
{
    public static void SetCache(string key, object value)
    {
        HttpContext.Current.Cache[key] = value;
        if (key == "some special key")
            WriteValueOnDisk(value);
    }
}


You can access the cache through HttpRuntime.Cache when you don't have an HttpContext available. However, at Application_End, i believe the cache is already flushed.

The solution Dima Shmidt outlines would be the best approach to store your cached values. That is by adding your items to cache with a CacheItemRemovedCallback, and store the values to disk there.


As an alternative solution you could store the data in Application object (Application[key]) or simply create a static class and use it to keep your data within app - in this case the data would sill be available upon Application_End.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜