I want to use MemoryCache
. I want to set some keys/values in MemoryCache
.
my values are important and expired at a specified time. for example 120 Seconds.
every 60 seconds my keys/values and expired time are updated(for 120 seconds). if some keys are not updated I want to find out what the key is then I call a function to alert the system admin.
What can I do?
2
Answers
I think you Can register a PostEvictionCallback to tackle your use case : https://learn.microsoft.com/en-us/dotnet/api/microsoft.extensions.caching.memory.cacheentryextensions.registerpostevictioncallback?view=dotnet-plat-ext-8.0
There is example in Microsoft Doc:
https://learn.microsoft.com/en-us/aspnet/core/performance/caching/memory?view=aspnetcore-8.0#memorycacheentryoptions
You can achieve this by using a combination of MemoryCache and a background task that periodically checks for expired keys and takes appropriate actions.
You can get an idea from this code:
You can adjust the expiration time and update interval according to your requirements. Additionally, you may need to handle concurrency and synchronization if multiple threads are accessing the cache concurrently.