You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET Core 3.1下IMemoryCache的TryGetValue与Set方法线程安全性及文档位置咨询

Thread Safety of IMemoryCache.TryGetValue and Set in .NET Core 3.1

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 IMemoryCache is thread-safe and intended for use in multi-threaded scenarios.

内容的提问来源于stack exchange,提问作者Josh Williamson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 21:07:43