Reputation: 411
I have an object that behaves like a cache. It could fill whole available memory if needed.
I'd like to be able to give memory back to an OS on-need basis. So if there is a problem with any other allocation, VM (or GC or whoever) should ask my 'cache' to shrink before failing with OutOfMemory exception.
How can I do it in C#?
Upvotes: 3
Views: 316
Reputation: 1494
I would suggest to keep objects in cache for a limited time, and use built-in cache.
Upvotes: 0
Reputation: 1038710
I would recommend you to use the built-in Cache instead of reinventing the wheel. It automatically takes care of situations like this: it will expire items based on their priority if memory starts to run low. It is also very extensible and you can easily make it distributed with popular providers such as memcached.
Note that System.Runtime.Caching
is only available in .NET 4.0 only. Other caches are available in earlier versions, such as Enterprise library, System.Web.Caching, Velocity, ...
Upvotes: 9
Reputation: 3548
Very interesting question. Have you tried to play with WeakReferences? It looks like that is exactly what you need.
Upvotes: 0
Reputation: 9639
How about a configurable maximum cache size; when your cache reaches the max, you remove the oldest items from it. The max should be defined in terms that make sense for your cache, e.g, max items in the cache, max memory use etc.
Upvotes: 0