内存缓存问题。TryGetValue 返回 false

ant*_*ant 6 c# .net-core

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

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

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

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

Fer*_*min 6

Based on the source code for TryGetValue() it will return false if null is returned when it checks type if (result is TItem item). However, the .Count property would return 1. (thanks to @jgoday comment for these details).

An alternative is to have a 'null value' (e.g. Guid.NewGuid()) that you can use to represent a null value, this way something is entered into the cache so you can verify whether it has ever been added.

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;
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 在 dotnet.core 中并未真正记录在案,但基于源代码(https://github.com/aspnet/Caching/blob/master/src/Microsoft.Extensions.Caching.Abstractions/MemoryCacheExtensions.cs),TryGetValue 扩展将如果值为 null,则永远不会返回 true(null 是 Titem 始终为 false),但是 Count 属性将返回 1。这似乎有点不一致...... (3认同)