我们正在使用 .NET Core 3.1 和Microsoft.Extensions.Caching.Memory.IMemoryCache https://www.nuget.org/packages/Microsoft.Extensions.Caching.Memory/3.1.24(v3.1.24) 及其实施Microsoft.Extensions.Caching.Memory.MemoryCache
。我正在阅读有关的文档内存缓存 https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-3.1。我没有发现任何提及线程安全的内容IMemoryCache
。这是我们如何使用它的片段:
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
线程安全?文档中哪里提到了它?
TL;DR 是的,它是线程安全的。
如果你查看这些的源代码Set
扩展方法,当与Microsoft.Extensions.Caching.Memory.IMemoryCache
您会找到 MemoryCache.SetEntry 方法。
里面有一个CoherentState
由并发字典支持的类,用于实际存储缓存条目。还有大量代码(和注释!)讨论其他线程上发生的更新/清除。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)