Josh Williamson
Josh Williamson

Reputation: 51

Is Microsoft.Extensions.Caching.Memory.IMemoryCache thread safe

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?

Upvotes: 5

Views: 4115

Answers (2)

Mark Jerzykowski
Mark Jerzykowski

Reputation: 982

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.

Upvotes: 3

Related Questions