Using 'HttpContext.Current.Cache' safely

前端 未结 3 1987
小蘑菇
小蘑菇 2021-02-13 06:57

I am using Cache in a web service method like this:

var pblDataList = (List)HttpContext.Current.Cache.Get(\"pblDataList\");

if (pblDa         


        
3条回答
  •  悲&欢浪女
    2021-02-13 07:52

    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.

    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.

提交回复
热议问题