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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, the MemoryCache class is thread safe:
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
Getto fetch the dictionary and starts reading from it, thread2 usesGetto 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.