© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•10mo ago•
7 replies
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()
        );
    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
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
GetOrCreateAsync
return null if my
GetProblematicIndicatorDisplaysAsync
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));
var options = new MemoryCacheEntryOptions().SetAbsoluteExpiration(DateTime.Now.AddMinutes(10));


Passing that as the last parameter of the
GetorCreateAsync
GetorCreateAsync
call (also, should
options
options
become a field of my class?). Any advice or warnings about using the
IMemoryCache
IMemoryCache
would be appreciated, thanks!
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

✅ IMemoryCache missing Contains?
C#CC# / help
2y ago
❔ How to use abstract factories with DI properly?
C#CC# / help
4y ago
How do I properly use DI `.AddLogging`?
C#CC# / help
4y ago
✅ Caching with IMemoryCache, is there a difference?
C#CC# / help
3y ago