Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Runtime.Caching.MemoryCache - is locking necessary

Tags:

.net

caching

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?

like image 921
Ben Foster Avatar asked Mar 08 '11 15:03

Ben Foster


People also ask

Is MemoryCache set thread-safe?

MemoryCache is threadsafe. Multiple concurrent threads can read and write a MemoryCache instance.

Is MemoryCache shared?

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.

How does MemoryCache work C#?

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.

Is MemoryCache per user?

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).


2 Answers

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.

like image 89
Hans Passant Avatar answered Nov 15 '22 21:11

Hans Passant


According to the new documentation the MemoryCache class IS thread safe.

MSDN

Microsoft connect

like image 42
Davide Icardi Avatar answered Nov 15 '22 20:11

Davide Icardi