1

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.

Luis
  • 5,979
  • 2
  • 31
  • 51

1 Answers1

0

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;
            });
alastairtree
  • 3,960
  • 32
  • 49
  • In .NET 6 this does not work, If you do `entry.AbsoluteExpirationRelativeToNow = TimeSpan.Zero;` then you get System.ArgumentOutOfRangeException Message=The relative expiration value must be positive. (Parameter 'AbsoluteExpirationRelativeToNow') Actual value was 00:00:00. Source=Microsoft.Extensions.Caching.Memory but if you do `entry.AbsoluteExpiration = DateTimeOffset.UtcNow.AddSeconds(-1);` then you get away with it. It's still a bit of hack. – Anthony Jul 08 '23 at 10:52