Is MemoryCache.Set() thread-safe?

前端 未结 2 891
南旧
南旧 2020-12-13 18:25

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 .

相关标签:
2条回答
  • 2020-12-13 18:49

    The documentation for MemoryCache states:

    This type is thread safe.

    0 讨论(0)
  • 2020-12-13 18:52

    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.

    0 讨论(0)
提交回复
热议问题