4

We are using .NET Core 3.1 and Microsoft.Extensions.Caching.Memory.IMemoryCache (v3.1.24) and its implementation Microsoft.Extensions.Caching.Memory.MemoryCache. I was reading the documentation about IMemoryCache. I didn't find any mention of thread safety of IMemoryCache. This is the snippet of how we use it:

public class TestController : Controller
{
    private readonly IMemoryCache _memoryCache;

    public TestController(IMemoryCache memoryCache)
    {
        _memoryCache = memoryCache;
    }

    [HttpGet]
    public IActionResult TestAction()
    {
        string key = "abc";
        if (!_memoryCache.TryGetValue(key, out string cachedString))
        {
            cachedString = "new string";
            _memoryCache.Set(key, cachedString, TimeSpan.FromMinutes(15));
        }
        return Ok();
    }
}

Are _memoryCache.TryGetValue and _memoryCache.Set thread safe? Where is it mentioned in documentation?

  • `IMemoryCache` is an interface. What actual implementation are you using? [MS-provided MemoryCache](https://stackoverflow.com/a/20150112/1043380)? – gunr2171 May 09 '22 at 12:47
  • I edited the question. We are using `Microsoft.Extensions.Caching.Memory.MemoryCache` implementation. – Josh Williamson May 09 '22 at 12:50
  • 1
    it is a fair observation that the docs should call this out explicitly; "it should be" is all I can say – Marc Gravell May 09 '22 at 12:50

2 Answers2

1

TL;DR Yes, it's thread-safe.

If you look in to the source code for those Set extension methods, when used with Microsoft.Extensions.Caching.Memory.IMemoryCache you'll find the MemoryCache.SetEntry method.

In there, there is a CoherentState class that's backed by a Concurrent Dictionary for actual storage of cache entries. There's also a fair amount of code (and comments!) discussing updates/clears happening on other threads.

Mark Jerzykowski
  • 812
  • 8
  • 15