.NET Core 3.1下IMemoryCache的TryGetValue与Set方法线程安全性及文档位置咨询
Great question! Let's break this down clearly:
Core Answer
Yes, both TryGetValue and Set methods of IMemoryCache (specifically the MemoryCache implementation you're using, version 3.1.24) are thread-safe. The MemoryCache class is designed to handle concurrent access from multiple threads without requiring additional locking from your side for individual operations.
Important Note on Your Code
While the individual methods are thread-safe, the pattern you're using in your TestAction has a race condition: multiple threads could pass the TryGetValue check at the same time, leading all of them to execute the Set call. Even though Set is safe, this means you might end up initializing the cached value multiple times unnecessarily.
To fix this, use the atomic GetOrCreate (or GetOrCreateAsync for async workloads) method instead—it handles the check and creation in a thread-safe, atomic operation:
[HttpGet] public IActionResult TestAction() { string key = "abc"; var cachedString = _memoryCache.GetOrCreate(key, entry => { entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(15); return "new string"; }); return Ok(); }
Where to Find Official Documentation
You might have missed the thread safety note because it's documented on the MemoryCache implementation class rather than the IMemoryCache interface itself. Here's where to locate it:
- In the official .NET API docs for
MemoryCache, the Thread Safety section states that all public static members are thread-safe, and all public instance members are also thread-safe. - The .NET Core caching guidance documentation also explicitly mentions that
IMemoryCacheis thread-safe and intended for use in multi-threaded scenarios.
内容的提问来源于stack exchange,提问作者Josh Williamson

