LazyCache:如何防止特定项目添加到缓存中

问题描述 投票:0回答:2

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

            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
2个回答
0
投票

您可以使用 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;
            });

0
投票

除了之前的答案之外,

entry.AbsoluteExpirationRelativeToNow = TimeSpan.Zero
在.NET 7 / [电子邮件受保护]下工作正常

output = _cache.GetOrAdd(
    "GetRecordUri" + 123, entry => {
        var record = internalGetRecordUri();
        if (record == null)
            entry.AbsoluteExpirationRelativeToNow = TimeSpan.Zero; // Immediate expiration
        else
            entry.AbsoluteExpirationRelativeToNow = new TimeSpan(1, 0, 0, 0);
            
        return record;
    });
© www.soinside.com 2019 - 2024. All rights reserved.