Reputation: 34800
Do we still need to implement locking when working with the System.Runtime.Caching.MemoryCache
e.g. calling Contains(key);
or is it already thread safe?
Upvotes: 9
Views: 3738
Reputation: 941585
The "Thread Safety" section in the MSDN Library article about a class documents this:
Any instance members are not guaranteed to be thread safe.
This is quite normal for .NET classes, the documentation is boilerplate and in a few selected cases uninformative. That was the case for MemoryCache as well until the documentation got updated. The Connect feedback article linked by Davide is helpful to clear this up:
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.
Upvotes: 10
Reputation: 12209
According to the new documentation the MemoryCache class IS thread safe.
Upvotes: 7