我可以翻译成中文。"HttpContext.Current.Cache"一旦获取,是否可以始终可用?

4

我有一个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;
        }
    }
}

因此,在第一次向网站发出请求之前,不会应用任何缓存,但是一旦至少有一个请求被发出,HttpContext.Current.Cache的引用将被保存,所有后台服务器操作都将能够访问缓存。
问题:
我可以相信一旦获得HttpContext.Current.Cache就会始终有效吗?
非常感谢。对于这个想法的任何想法或评论都非常欢迎!
1个回答

10

建议使用HttpRuntime.Cache代替HttpContext.Current.Cache - 两个属性指向同一缓存,但前者不像后者那样需要当前上下文。

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


2
哦,我的天啊...我找那个方法找了好几年!!!现在终于找到了...非常感谢! - Budda

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接