开发者

Application level cached objects should be threadsafe?

开发者 https://www.devze.com 2023-04-13 00:20 出处:网络
I am thinking to use HttpContext.Current.Cache which ha开发者_Go百科s application level scope. I know that Cache object is thread safe but the thing that i don\'t understand is cached objects are not

I am thinking to use HttpContext.Current.Cache which ha开发者_Go百科s application level scope. I know that Cache object is thread safe but the thing that i don't understand is cached objects are not thread safe so how it is possible to use and modify them thread safely ???


As per MSDN article the Cache type is thread safe but caching not thread safe object may cause unexpected errors.

Here is very good thread (stackoverflow) on Thread-safe cache libraries for .NET and MSDN article on Object Caching (Sharepoint) - Object Caching Techniques


It is your own responsibility to make sure that the objects placed in the cache are thread-safe.


If different threads are going to use and modify the cached objects concurrently then you will need some application level protocol. This can be either as simple as lock(cachedObject) {....}

If you can determine that something in the cache is only accessed by a single thread at a time or that it cannot be modified (because it is immutable) then you don't need anything further.

What it means for HttpContext.Current.Cache to be threadsafe is that multiple threads can get and put stuff in it concurrently. So if you want some co-ordination between multiple keys then you will need some higher level locking.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号