How to prevent specific items to be added to the cache. In my case I am looking at preventing null returns to be added to the cache. This is what I am doing at the moment:
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);
}
}
I am sure there are better ways as implementing locks this way defeats the purpose of using LazyCache in the first place.
You can achieve this using the MemoryCacheEntryOptions callback to generate the cache item and setting the expiry date to be in the past if it is null: