安全使用'HttpContext.Current.Cache' [英] Using 'HttpContext.Current.Cache' safely
问题描述
我正在像这样的Web服务方法中使用Cache
:
I am using Cache
in a web service method like this:
var pblDataList = (List<blabla>)HttpContext.Current.Cache.Get("pblDataList");
if (pblDataList == null)
{
var PBLData = dc.ExecuteQuery<blabla>(@"SELECT blabla");
pblDataList = PBLData.ToList();
HttpContext.Current.Cache.Add("pblDataList", pblDataList, null,
DateTime.Now.Add(new TimeSpan(0, 0, 15)),
Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);
}
但是我想知道,这段代码是线程安全的吗? Web服务方法由多个请求者调用.而且,在高速缓存为空时,一个请求者可能会尝试同时检索数据并将其添加到Cache
.
But I wonder, is this code thread-safe? The web service method is called by multiple requesters. And more then one requester may attempt to retrieve data and add to the Cache
at the same time while the cache is empty.
查询需要5到8秒.是否可以在此代码周围引入lock语句来防止任何可能的冲突? (我知道多个查询可以同时运行,但是我想确保一次只运行一个查询.)
The query takes 5 to 8 seconds. Would introducing a lock statement around this code prevent any possible conflicts? (I know that multiple queries can run simultaneously, but I want to be sure that only one query is running at a time.)
推荐答案
缓存对象是线程安全的,但是HttpContext.Current
在后台线程中将不可用.您在这里,从代码段中看不出来您是否确实在使用后台线程,但是如果您现在就使用或决定在将来某个时候使用,则应牢记这一点.
The cache object is thread-safe but HttpContext.Current
will not be available from background threads. This may or may not apply to you here, it's not obvious from your code snippet whether or not you are actually using background threads, but in case you are now or decide to at some point in the future, you should keep this in mind.
If there's any chance that you'll need to access the cache from a background thread, then use HttpRuntime.Cache instead.
此外,尽管高速缓存上的各个操作都是线程安全的,但是顺序查找/存储操作显然不是原子的.是否需要是原子的取决于您的特定应用程序.如果同一查询多次运行可能是一个严重的问题,即,如果它产生的负载超过了数据库的处理能力,或者请求返回立即被覆盖的数据而成为问题,缓存,那么您可能想在整个代码块上放置一个锁.
In addition, although individual operations on the cache are thread-safe, sequential lookup/store operations are obviously not atomic. Whether or not you need them to be atomic depends on your particular application. If it could be a serious problem for the same query to run multiple times, i.e. if it would produce more load than your database is able to handle, or if it would be a problem for a request to return data that is immediately overwritten in the cache, then you would likely want to place a lock around the entire block of code.
但是,在大多数情况下,您确实希望首先进行分析,然后看看这是否确实是一个问题.大多数Web应用程序/服务都不关心缓存的这一方面,因为它们是无状态的,并且缓存是否被覆盖也无关紧要.
However, in most cases you would really want to profile first and see whether or not this is actually a problem. Most web applications/services don't concern themselves with this aspect of caching because they are stateless and it doesn't matter if the cache gets overwritten.
这篇关于安全使用'HttpContext.Current.Cache'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!