如何防止特定项目添加到缓存中。就我而言,我正在考虑防止将空返回添加到缓存中。这就是我现在正在做的事情:
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 的目的。
您可以使用 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;
});
除了之前的答案之外,
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;
});