5

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?

Adi Lester
  • 24,731
  • 12
  • 95
  • 110

1 Answers1

3

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.

Adam
  • 16,089
  • 6
  • 66
  • 109
  • I've tested this with `char[]`, and items were evicted even though I used `new CacheItemPolicy()`. Either way, in order to add an item to the cache, I have to supply a `CacheItemPolicy` parameter. What value do I need to pass then in order to get the requested behavior? – Adi Lester Jan 05 '12 at 19:23
  • This still doesn't give me the requested behavior. I don't want to explicitly set the time when the items will expire - I want them to expire if the memory limit, as defined in `app.config`, was exceeded. Also, I'm pretty sure you're wrong about the items expiring at 31/12/9999 11:59:59 PM +00:00, because as I said in my comment above, I did get items to expire even when I added them with the policy `new CacheItemPolicy()`. – Adi Lester Jan 06 '12 at 11:36