I’m working with the .NET 4.0 MemoryCache class in an application and trying to limit the maximum cache size, but in my tests it does not appear that the cache is actually o
I've encountered this issue as well. I'm caching objects that are being fired into my process dozens of times per second.
I have found the following configuration and usage frees the items every 5 seconds most of the time.
App.config:
Take note of cacheMemoryLimitMegabytes. When this was set to zero, the purging routine would not fire in a reasonable time.
<system.runtime.caching>
<memoryCache>
<namedCaches>
<add name="Default" cacheMemoryLimitMegabytes="20" physicalMemoryLimitPercentage="0" pollingInterval="00:00:05" />
</namedCaches>
</memoryCache>
</system.runtime.caching>
Adding to cache:
MemoryCache.Default.Add(someKeyValue, objectToCache, new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddSeconds(5), RemovedCallback = cacheItemRemoved });
Confirming the cache removal is working:
void cacheItemRemoved(CacheEntryRemovedArguments arguments)
{
System.Diagnostics.Debug.WriteLine("Item removed from cache: {0} at {1}", arguments.CacheItem.Key, DateTime.Now.ToString());
}