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:
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!1 Reply
https://source.dot.net/#Microsoft.Extensions.Caching.Abstractions/MemoryCacheExtensions.cs,224 if you look at the implementation of the extension method you used, you can see that it wraps the entire CacheEntry disposal for you, so implicitly you're doing the wrong thing, but the surface API is just easier to use.
For the nullability: It's perfectly valid to cache
null
on a key
So even if you never intend to actually cache null
, there's no rule which would keep you from doing it, so the memorycache methods also won't pretend that the value is always non-null
If you know it's never going to be null you can always ! it
For the entries, you can either pass them as a separate parameter and it will apply all of the options to the entry
Or, within the second parameter callback, you can set the options on the entry directly
So it's basically just a way to pass an entire options object if you have that stored for reuse somewhere