Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

LazyCache prevent null items being added to cache

I have a method that will expire null items immediately, however I wanted to know if there w as better way to do this for all memory cache items instead of repeating the same code over and over

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

The code in bold seems redundant Is there an extension that I can use that will do the same?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can place this check in separate method:

public void SetAbsoluteExpiration(Entry entry, object value) // change Entry to correct type
{
    if (value is null) // or if (value == null)
        // expire immediately
        entry.AbsoluteExpirationRelativeToNow = new TimeSpan(-1, 0, 0, 0);
    else
        entry.AbsoluteExpirationRelativeToNow = new TimeSpan(1, 0, 0, 0);
}

And call it everywhere you need:

 output = _cache.GetOrAdd(
    "GetRecordUri" + 123, entry => {
        var record = internalGetRecordUri();
        
        SetAbsoluteExpiration(entry, record);

        return record;
    });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading