1

I thought the way the MemoryCache class worked was it held whatever you placed in it in memory as long as the CachePolicy was still met, and as long as memory conditions allow.

After running some tests I'm not sure MemoryCache takes any action when memory conditions are low.

I can run the following code in a console app:

        MemoryCache cache = MemoryCache.Default;
        CacheItemPolicy p = new CacheItemPolicy()
        {
            AbsoluteExpiration = ObjectCache.InfiniteAbsoluteExpiration
        };

        for (int i=0; i < 1000000; i++)
        {
            Console.WriteLine(i);
            string s = new string('0', 50000);
            cache.Add(new CacheItem(i.ToString(), s), p);
        }

After about 30K iterations, I get a System.OutOfMemoryException.

Why doesn't MemoryCache and the GC release the objects stored when memory conditions are low?

Aheho
  • 12,622
  • 13
  • 54
  • 83

1 Answers1

1

You should take a peek at the CacheMemoryLimitMegabytes property or the PhysicalMemoryLimitPercentage property.

However in earlier version of the MemoryCache there have been reported problems with the way it checks the memory pressure. Have a peek at this question

John Mitchell
  • 9,653
  • 9
  • 57
  • 91
  • I added a callback on Cache deletion and that was informing. When a unhandled OutOfMemoryException is thrown, MemoryCache starts deleting Items. Of course by then it's too late. If you add a try catch block to handle the outofMemoryException, MemoryCache no longer deletes any items. – Aheho Dec 31 '17 at 15:50
  • 1
    It's like quantum particle physics where observation changes the behavior. – Aheho Dec 31 '17 at 15:51