Reputation: 4574
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:
Upvotes: 2
Views: 270
Reputation: 38528
iOS will call DidReceiveMemoryWarning()
on your UIViewController subclasses when you are running low on memory, allowing you to free up resources.
Android will call OnLowMemory()
on your Activity subclasses.
I'm not sure what the equivalent on Windows Phone is, but I wouldn't be surprised if they have something similar.
Upvotes: 3