MemoryCache Thread Safety, Is Locking Necessary?
The default MS-provided MemoryCache
is entirely thread safe. Any custom implementation that derives from MemoryCache
may not be thread safe. If you're using plain MemoryCache
out of the box, it is thread safe. Browse the source code of my open source distributed caching solution to see how I use it (MemCache.cs):
https://github.com/haneytron/dache/blob/master/Dache.CacheHost/Storage/MemCache.cs
While MemoryCache is indeed thread safe as other answers have specified, it does have a common multi threading issue - if 2 threads try to Get
from (or check Contains
) the cache at the same time, then both will miss the cache and both will end up generating the result and both will then add the result to the cache.
Often this is undesirable - the second thread should wait for the first to complete and use its result rather than generating results twice.
This was one of the reasons I wrote LazyCache - a friendly wrapper on MemoryCache that solves these sorts of issues. It is also available on Nuget.