【问题标题】:LazyCache: How to prevent specific item to be added to the cacheLazyCache:如何防止将特定项目添加到缓存中
【发布时间】:2020-09-28 22:42:08
【问题描述】:

如何防止将特定项目添加到缓存中。就我而言,我正在考虑防止将空返回添加到缓存中。这就是我目前正在做的事情:

            Func<long?> internalGetRecordUri =() =>
            {
                //it can return null here
            };

            long? output; 

            lock (_lock)
            {
                output = _cache.GetOrAdd(
                    "GetRecordUri" + applicationId,
                    internalGetRecordUri, new TimeSpan(1, 0, 0, 0));
                if (output == null)
                {
                    _cache.Remove("GetRecordUri" + applicationId);
                }
            }

我确信有更好的方法来实现锁,这种方式首先破坏了使用 LazyCache 的目的。

【问题讨论】:

    标签: c# memorycache lazycache


    【解决方案1】:

    您可以使用 MemoryCacheEntryOptions 回调来生成缓存项并将过期日期设置为过去(如果它为空):

            output = _cache.GetOrAdd(
                "GetRecordUri" + 123, entry => {
                    var record = internalGetRecordUri();
                    if(record == null)
                        // expire immediately
                        entry.AbsoluteExpirationRelativeToNow = new TimeSpan(-1, 0, 0, 0);
                    else
                        entry.AbsoluteExpirationRelativeToNow = new TimeSpan(1, 0, 0, 0);
                    return record;
                });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-08
      • 2016-05-28
      • 2014-07-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多