Join GitHub today
GitHub is home to over 36 million developers working together to host and review code, manage projects, and build software together.Sign up
Question: Expiration allmost never happens on it's own in the background #248
I'm currently implementing a class which should mimic session timeouts. Before writing this on my own I've thought taking the IMemoryCache implementation should do the trick as well.
I'm having a plain vanilla asp.net core web api project. I've added the nuget package to project.json and added the following code:
Startup.cs -> services.AddMemoryCache(c => c.CompactOnMemoryPressure = false);
Then I'm going to use the ctor injected IMemoryCache instance in my class by TryGetValue to get out an existing item or Set() to add a new one.
I use RegisterPostEvictionCallback to run some code when the item expires and add an expiration token to be able to have a Reset() method which expires all items at once -> Clear()
The problem I'm having is that the items don't expire automatically. It needs another web api call that accesses the Set() method to trigger the evicted callback on the already expired items.
Why didn't the evicted callback fire when the item expired in first place? I can't afford to have another web api to trigger the session timeouts for the system.
What do I miss?
This is by design, there's no timer thread that actively scans the cache for expired items. We didn't want a timer always running on an otherwise idle site. Any activity on the cache (Get, Set, Remove) can trigger a background scan for expired items. A timer on the CancellationTokenSource (CancelAfter) would also remove the entry and trigger a scan for expired items.
Rather than using