My .NET application is running on Windows Phone, Android and iOS (via Mono).
I am looking for a way to detect low memory situations before OutOfMemory exception is thrown (or application just dies, which is what usually happens on mobile platforms).
My application has a way to instantly reduce memory usage by using a different code path. Unfortunately I need to know when to do so - I need to know that memory is low before I am shut down by the OS.
I am not looking for a silver bullet that will work 100% of the time. Anything that will reduce frequency of out-of-memory crashes is good.
For example, does the following make sense:
// Periodically (say once per a few seconds) execute the following:
try
{
byte[] probe = new byte[1 * 1024 * 1024];
}
catch (OutOfMemoryException)
{
// 1MB free block not found, choose low memory code path
}
This has the drawback of increasing the frequency of garbage collections. Is there a better way?
Nonsolutions:
- .NET MemoryFailPoint class, unfortunately it is not yet available in Mono and so is not an option.