Is MemoryCache.Set() thread-safe?
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?
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.
The documentation for MemoryCache
states:
This type is thread safe.
精彩评论