Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I rely that once obtained HttpContext.Current.Cache will be always valid?

I have an ASP.NET (4.0) web site that has few operations running on the server independently from users requests. I extensively use cache during web requests and keep objects inside of HttpContext.Current.Cache.

The problem is that for all threads that are not caused by user requests HttpContext.Current is null and I can't access Cache.

In order 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 1st request to the web site is made, no any caching will be applied, but once at least one request made, the reference to HttpContext.Current.Cache will be saved and all background server operations will be able to access cache.

Question:

Can I rely that once obtained HttpContext.Current.Cache will be always valid?

Thank you very much. Any ideas or comments with regards to the idea are more than welcome!

like image 529
Budda Avatar asked Dec 25 '22 20:12

Budda


1 Answers

Instead of using HttpContext.Current.Cache, I would recommend using HttpRuntime.Cache - both properties point to the same cache except the latter is not dependent on a current context like the former is.

If you're writing a general cache wrapper to be used in a number of different types of applications/services, you may want to take a look at ObjectCache and MemoryCache to see if they would be useful for your need.

like image 123
Russ Cam Avatar answered Dec 28 '22 11:12

Russ Cam