一旦获得HttpContext.Current.Cache总是有效的,我可以依赖吗?

Bud*_*dda 4 c# asp.net caching

我有一个ASP.NET(4.0)网站,在服务器上运行的操作很少,与用户请求无关.我在Web请求期间广泛使用缓存并将对象保留在HttpContext.Current.Cache中.

问题是,对于不是由用户请求引起的所有线程,HttpContext.Current为null,我无法访问Cache.

为了访问HttpContext.Current.Cache,我计划使用以下内容:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

因此,在对网站发出第一个请求之前,不会应用任何缓存,但是一旦至少发出一个请求,将保存对HttpContext.Current.Cache的引用,并且所有后台服务器操作都将能够访问缓存.

题:

一旦获得HttpContext.Current.Cache总是有效的,我可以依赖吗?

非常感谢你.任何关于这个想法的想法或评论都非常受欢迎!

Rus*_*Cam 10

而不是使用HttpContext.Current.Cache,我建议使用HttpRuntime.Cache- 两个属性都指向相同的缓存,除了后者不依赖于前者的当前上下文.

如果您正在编写一个通用缓存包装器以用于许多不同类型的应用程序/服务,您可能需要查看ObjectCacheMemoryCache查看它们是否对您的需求有用.

  • 我的天啊......我一直在寻找那些方法!现在我找到了...非常感谢! (2认同)