When does dot net's MemoryCache eviction occur? How can I simulate the eviction in console application? Whenever I try to add objects to the memory cache until eviction occurs I get OutofMemoryException instead.
See MemoryCacheElement
, that is what controls the default behavior if you don't pass in values to the NameValueCollection config
in the constructor or you use the default instance.
Looking through the defaults of the MemoryCacheElement
, it checks every two minutes (however it does go faster the closer you are to the high pressure limit). Once inside the timer's callback it will caculate the percentage to trim off of the MemoryCache and then will call MemoryCache.Trim(Int32)
using the calculated percentage.
One thing to note in the percentage calculation, if no Gen 2 garbage collections have happened the cache does not attempt to shrink itself.
It is very possible that the way your test console program was running it used up all the memory before a Gen 2 collection could occur or was still in the initial two minute slow mode to check on the memory pressure before it could clear items out.
If you would like to simulate a eviction just call
MemoryCache.Default.Trim(50);
And that will evict half of the cache from the default cache.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With