Can I rely that after receiving HttpContext.Current.Cache will always be valid?

I have an ASP.NET website (4.0) that performs several operations on the server regardless of user requests. I use cache extensively during web requests and store objects inside HttpContext.Current.Cache.

The problem is that for all threads not caused by user requests, HttpContext.Current is null, and I cannot access the cache.

To access HttpContext.Current.Cache, I plan to use the following:

class CacheWrapper { public void Insert(string key, Object obj) { Cache cache = CacheInstance; if (cache == null) { return; } cache.Insert(key, obj); } public Object Get(string key) { Cache cache = CacheInstance; if (cache == null) { return; } return cache.Get(key); } private Cache CacheInstance { get { if (_cache == null) { if (HttpContext.Current == null) { return null; } lock (_lock) { if (_cache == null) { _cache = HttpContext.Current.Cache; } } } return _cache; } } } 

Therefore, until the first request to the website is made, no caching will be applied, but as soon as one request is made, a link to HttpContext.Current.Cache will be saved, and all operations with the background server will be able to cache access.

Question:

Is it possible to rely that upon receipt of HttpContext.Current.Cache will always be valid?

Many thanks. Any ideas or comments regarding this idea are more than welcome!

+4
source share
1 answer

Instead of using HttpContext.Current.Cache I would recommend using HttpRuntime.Cache - both properties point to the same cache, except that the latter does not depend on the current context, such as the first.

If you are writing a general cache shell that will be used in several different types of applications / services, you can take a look at ObjectCache and MemoryCache to see if they will be useful for your needs.

+10
source

All Articles