36

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?

Timwi
  • 65,159
  • 33
  • 165
  • 230

2 Answers2

73

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 2
    I'm sorry for the bump, but I'm very curious as to how one should work around a case like that. Could you maybe elaborate a bit on that? – fuaaark Jul 10 '12 at 16:02
  • Massive necro but for anyone looking though this thread now, personally I would handle it by sync locking the atomic operations being done to the data structure. Say you need to iterate over a few objects and do updates, you would implement locking code around the block that does the cache update. – Marissa Mar 26 '14 at 03:27
  • In fact, as you said, the memory-cache itself is thread-safe, but one might store a data structure which is not thread-safe and this is not a problem with MemoryCache, it also applies to other caching frameworks too. – Alireza Maddah Oct 31 '14 at 07:13
12

The documentation for MemoryCache states:

This type is thread safe.

jason
  • 236,483
  • 35
  • 423
  • 525
  • 2
    OMG it really didn’t occur to me to look at the documentation for the *type* instead of the individual *methods*... – Timwi Jul 18 '11 at 19:23
  • 1
    @Timwi: No problem. Most type I've ever looked at do include in their documentation a statement to the effect of "the static members are thread safe, the instance members are not guaranteed to be." This particular class (`MemoryCache`) instead gives you the happy result you were looking for. – jason Jul 18 '11 at 19:26