gpt4 book ai didi

c# - 我可以相信一旦获得 HttpContext.Current.Cache 将永远有效吗?

转载 作者:太空狗 更新时间:2023-10-30 00:19:34 25 4
gpt4 key购买 nike

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

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

为了访问 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 将永远有效吗?

非常感谢。非常欢迎任何关于这个想法的想法或评论!

最佳答案

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

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

关于c# - 我可以相信一旦获得 HttpContext.Current.Cache 将永远有效吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18908342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com