【问题标题】:Can I rely that once obtained HttpContext.Current.Cache will be always valid?我可以相信一旦获得 HttpContext.Current.Cache 将始终有效吗?
【发布时间】:2013-09-20 03:27:27
【问题描述】:

我有一个 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 将永远有效吗?

非常感谢。任何关于这个想法的想法或 cmet 都非常受欢迎!

【问题讨论】:

    标签: c# asp.net caching


    【解决方案1】:

    我建议不要使用HttpContext.Current.Cache,而是使用HttpRuntime.Cache - 两个属性都指向同一个缓存,但后者不像前者那样依赖于当前上下文。

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

    【讨论】:

    • 我的天哪...我一直在寻找这种方法多年!!!!现在我找到了……非常感谢!
    • 没问题,乐于助人!
    猜你喜欢
    • 2021-09-07
    • 2023-03-24
    • 2011-10-16
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    • 2023-03-12
    • 1970-01-01
    相关资源
    最近更新 更多