Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Runtime.Caching doesn't release BitmapImage objects

I'm using the new System.Runtime.Caching library for caching in my application, and defined it as follows in the App.config:

<system.runtime.caching>
    <memoryCache>
        <namedCaches>
            <add name="MyCache" cacheMemoryLimitMegabytes="10"
                 physicalMemoryLimitPercentage="30" pollingInterval="00:00:10" />
        </namedCaches>
    </memoryCache>
</system.runtime.caching>

Then, from code I instantiate it like this: _cache = new MemoryCache("MyCache");

And add entries like this: _cache.Add(resourceName, resource, new CacheItemPolicy());

I use this cache to store BitmapImage objects, and to make sure the cache works properly, I've added ten BitmapImage objects to the cache, each holding an image of about 7MB. I then waited ten seconds for the polling to occur and checked the entries in the cache, but they were all there. Not a single object has been evicted.

Am I doing something wrong here? I know the settings are read from the App.config correctly. Is it possible that the BitmapImage instances themselves are small and only reference the image on the disk? And how does the cache determine what's the object's size?

like image 394
Adi Lester Avatar asked Oct 24 '22 14:10

Adi Lester


1 Answers

This is because you are adding to the cache with

new CacheItemPolicy()

This will override your values and give you the defaults, which is an AbsoluteExpiration of 31/12/9999 11:59:59 PM +00:00

to do it for 10 minutes you have 2 options

CacheItemPolicy item = new CacheItemPolicy();

item.SlidingExpiration = new TimeSpan(0, 10, 0);

or

item.AbsoluteExpiration = DateTime.Now.AddMinutes(10);

If you choose the sliding expiration the 10 minutes will reset if you update the object.

like image 161
Adam Avatar answered Oct 31 '22 11:10

Adam