如何检测 UWP 中的 "OutOfMemory" 或 ios 中 "didRecieveMemoryWarning" 的等效 UWP

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

UWP 应用程序中是否有 "didRecieveMemoryWarning" 或 ios 的等效项。

我想在 UWP 应用程序抛出任何错误之前检测 SystemOutOfMemory。

提前致谢。

努鲁尔

在UWP中,您可以使用AppMemoryUsageIncreased事件来检测,当应用程序的内存消耗增加到AppMemoryUsageLevel枚举中的更高值时引发。

Windows.System.MemoryManager.AppMemoryUsageIncreased += MemoryManager_AppMemoryUsageIncreased;

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

是的,我们需要使用 MemoryManager.AppMemoryUsageIncreased 事件,感谢@Faywang - MSFT 的回答,但我们需要做更多的工作。

即使在应用程序启动时也会调用此 MemoryManager.AppMemoryUsageIncreased。我对这种行为有点困惑,最后发现我们需要检查该事件中的内存使用情况。

这是我使用的确切代码

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();
    }
}

这是我得到这个答案的帖子。 How to detect "OutOfMemory" warning in UWP app