How to detect "OutOfMemory" in UWP or UWP equivalent for "didRecieveMemoryWarning" in ios

192 Views Asked by At

Is there any equivalent in UWP app for "didRecieveMemoryWarning" of ios.

I would like to detect SystemOutOfMemory in UWP application , before it throws any error.

Thanks in advance.

Noorul

2

There are 2 best solutions below

0
Noorul On BEST ANSWER

Yes , we need to use MemoryManager.AppMemoryUsageIncreased event, thanks to @Faywang - MSFT for the answer , but we need to do little more work.

This MemoryManager.AppMemoryUsageIncreased will be called even while app launch . I am bit confused of this behavior, finally found that we need to check for memory usage inside that event.

here is the exact code, which i used

private void MemoryManager_AppMemoryUsageIncreased(object sender, object e)
{
    // Obtain the current usage level
    var level = MemoryManager.AppMemoryUsageLevel;

    // Check the usage level to determine whether reducing memory is necessary.
    // Memory usage may have been fine when initially entering the background but
    // the app may have increased its memory usage since then and will need to trim back.
    if (level == AppMemoryUsageLevel.OverLimit || level == AppMemoryUsageLevel.High)
    {
        HandleOutOfMemory();
    }
}

Here is the thread in which I got this answer. How to detect "OutOfMemory" warning in UWP app

2
Faywang - MSFT On

In UWP, you can use AppMemoryUsageIncreased event to detect, it is raised when the app's memory consumption has increased to a higher value in the AppMemoryUsageLevel enumeration.

Windows.System.MemoryManager.AppMemoryUsageIncreased += MemoryManager_AppMemoryUsageIncreased;

private void MemoryManager_AppMemoryUsageIncreased(object sender, object e)
{
     // do something            
}