I'm trying to use .NET System.Runtime.Caching.MemoryCache (.NET Framework 4.7.2). I'm creating my own instance and set memory limit by using CacheMemoryLimitMegabytes parameter.
I use quite short keys - about 50 characters in average. Cached data is just long values (DB record IDs).
I use CacheItemPolicy with SlidingExpiration set to 15 minutes and RemovedCallback set to my method so I can log items evictions.
In my unit tests everything works fine. I set cache memory limit to 1 MB (just for testing) and I'm able to store thousands of items before eviction starts.
But when I try to use MemoryCache in application on dev server and set memory cache limit to 1 MB cache, I experience eviction after adding approximately 10 items to cache.
I tried to measure memory used by cache by approach described here:
In unit test, it reports reasonable values, but when I used my solution with memory cache on dev server, I get approx. 4.5 MB just after adding single item to cache. I even tried to call GC.Collect(2, GCCollectionMode.Forced) before checking ApproximateSize of _sizedRefMultiple, but still getting this value.
And because eviction relies on values returned from ApproximateSize as well, cache starts evicting items almost immediately. So I suspect that issue is caused by value reported by ApproximateSize.
Has anyone experienced similar behaviour? Do you have any tips what to check?