LazyCache: How to prevent specific item to be added to the cache

707 Views Asked by At

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.

1

There are 1 best solutions below

1
On

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:

        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;
            });