如何防止将特定项添加到缓存中。在我的例子中,我考虑的是防止将null返回添加到缓存中。这就是我目前正在做的事情:
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的目的。
发布于 2021-01-03 12:08:48
您可以使用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;
});
https://stackoverflow.com/questions/64110551
复制相似问题