c# - 内存缓存问题。 TryGetValue 返回 false

标签 c# .net-core

在此代码片段中,我只是将 null 放入 MemoryCache,然后检查此键是否存在:

        var _cache = new MemoryCache(new MemoryCacheOptions());
        _cache.Set<string>(cacheKey, null);
        var isInCache = _cache.TryGetValue(cacheKey, out string nothing);

isInCache 在这种情况下为 false。这种行为是预期的吗?

我使用 .NET Core 2.2 控制台应用程序。

最佳答案

基于source code对于 TryGetValue(),如果在检查类型 if (result is TItem item) 时返回 null,它将返回 false。但是,.Count 属性将返回 1。(感谢 @jgoday 对这些细节的评论)。

另一种方法是使用一个“空值”(例如 Guid.NewGuid())来表示一个空值,这样就可以将某些内容输入到缓存中,以便您可以验证是否曾经添加过。

public class MyCache
{
  private MemoryCache _cache = new MemoryCache(new MemoryCacheOptions());
  private string nullValue = Guid.NewGuid().ToString();

  public void Set(string cacheKey, string toSet)
    => _cache.Set<string>(cacheKey, toSet == null ? nullValue : toSet);

  public string Get(string cacheKey)
  {
    var isInCache = _cache.TryGetValue(cacheKey, out string cachedVal);
    if (!isInCache) return null;

    return cachedVal == nullValue ? null : cachedVal;
  }
}

关于c# - 内存缓存问题。 TryGetValue 返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55221262/

相关文章:

.net - 不支持文化1033(0x0409)

c# - 扩展方法中的 ILoggerFactory - 生命周期和处置

c# - 如何重定向 Powershell 的输出

web-services - 在.Net Core Web应用程序中获取移动地理位置

c# - 获取具有动态文件夹名称的特殊文件夹

c# - ASP.NET Core 路由中间件将租户名称放在 url 中

javascript - 错误 : $injector:modulerr ASP. 网络核心

c# - 在哪里验证 ASP.Net Core 应用程序中的 AutoMapper 配置?

c# - Automapper 展开到列表

c# - 如何使用 WPF 文本框实现捕获和显示当前按键?