gpt4 book ai didi

c# - Microsoft.Extensions.Caching.Memory.IMemoryCache 线程安全吗

转载 作者:行者123 更新时间:2023-12-05 05:42:00 24 4
gpt4 key购买 nike

我们正在使用 .NET Core 3.1 和 Microsoft.Extensions.Caching.Memory.IMemoryCache (v3.1.24) 及其实现 Microsoft.Extensions.Caching.Memory.MemoryCache。我正在阅读有关 IMemoryCache 的文档.我没有发现任何关于 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();
}
}

_memoryCache.TryGetValue_memoryCache.Set 线程安全吗?文档中哪里提到了它?

最佳答案

我也有同感。 ConcurrentDictionary(IMemoryCache 包装的内容)是线程安全的,但下面的链接表明我们需要使用信号量以避免竞争条件。这让它看起来好像不是,这令人困惑。据我所知,ConcurrentDictionary 本身是线程安全的,但我们对它的实现可能不是,所以我们需要使用信号量。我不喜欢那样;我希望 Microsoft 会简单地为我们创建信号量,但就这样吧。

https://learn.microsoft.com/en-us/dotnet/core/extensions/caching#photo-service-scenario

关于c# - Microsoft.Extensions.Caching.Memory.IMemoryCache 线程安全吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72172240/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com