【发布时间】: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 都非常受欢迎!
【问题讨论】: