内存缓存问题。 TryGetValue返回假

时间:2019-03-18 12:19:28

标签: 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控制台应用程序。

1 个答案:

答案 0 :(得分:4)

基于TryGetValue()的{​​{3}},如果在检查类型false时返回null,它将返回if (result is TItem item)。但是,.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;
  }
}