Is MemoryCache.Set() thread-safe?

旧城冷巷雨未停 提交于 2019-11-27 11:31:23

问题


The MSDN documentation for MemoryCache.Set unfortunately doesn’t state explicitly whether it is thread-safe or not.

Is it safe to use .Get() and .Set() from several threads without an explicit lock?


回答1:


Yes, the MemoryCache class is thread safe:

System.Runtime.Caching.MemoryCache is threadsafe. Multiple concurrent threads can read and write a MemoryCache instance. Internally thread-safety is automatically handled to ensure the cache is updated in a consistent manner.

What this might be referring to is that data stored within the cache may itself not be threadsafe. For example if a List is placed in the cache, and two separate threads both get a reference to the cached List, the two threads will end up stepping on each other if they both attempt to update the list simultaneously.

This being said the Get and Set methods are thread safe but if the data structure you might be storing into this cache is not thread safe you might get into trouble. Imagine for example that you stored a dictionary inside this cache. Then while thread1 uses Get to fetch the dictionary and starts reading from it, thread2 uses Get to fetch this same dictionary and tries to write to it. While the Get operation will be thread safe what will happen next could be pretty nasty.




回答2:


The documentation for MemoryCache states:

This type is thread safe.



来源:https://stackoverflow.com/questions/6738151/is-memorycache-set-thread-safe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!