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#?
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, ...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With