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?
MemoryCache is threadsafe. Multiple concurrent threads can read and write a MemoryCache instance.
MemoryCache does not allow you to share memory between processes as the memory used to cache objects is bound to the application pool. That's the nature of any in-memory cache implementation you'll find. The only way to actually use a shared cache is to use a distributed cache.
In-Memory Cache is used for when you want to implement cache in a single process. When the process dies, the cache dies with it. If you're running the same process on several servers, you will have a separate cache for each server. Persistent in-process Cache is when you back up your cache outside of process memory.
The ASP.NET Session object is per user key/value storage, whereas MemoryCache is an application level key/value storage (values are shared among all users).
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.
According to the new documentation the MemoryCache class IS thread safe.
MSDN
Microsoft connect
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With