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!
Budda source share