C#C
C#8mo ago
Canyon

How to properly use IMemoryCache?

Hi, all:

I'm working on improving latency for a Razor Page page load, which I can immediately do by caching query results. I've read this: https://www.learnrazorpages.com/razor-pages/caching, but I don't entirely understand how to:

  • Manage the lifetime of the cache disposable
  • Asynchronously get or create an entry
As an example, I have the following:
    public List<IndicatorDisplayExternal> IndicatorDisplays { get; set; } = [];
    private const string _indicatorDisplayKey = "IndicatorDisplays";
...
        IndicatorDisplays = await _memoryCache.GetOrCreateAsync(
            _indicatorDisplayKey,
            async entry => await _indicatorService.GetProblematicIndicatorDisplaysAsync()
        );


My main questions with this:
  • I didn't use a using statement like the page instructs with managing cache entries, is this okay?
  • The compiler is warning me of a possible null reference assignment, but how can GetOrCreateAsync return null if my GetProblematicIndicatorDisplaysAsync will never return null?
Once I get this sorted I'd like to set the cache entry to expire after some time. Would that just look like:

var options = new MemoryCacheEntryOptions().SetAbsoluteExpiration(DateTime.Now.AddMinutes(10));

Passing that as the last parameter of the GetorCreateAsync call (also, should options become a field of my class?). Any advice or warnings about using the IMemoryCache would be appreciated, thanks!
Was this page helpful?