如何防止OutOfMemoryException

本文关键字:OutOfMemoryException 何防止 | 更新日期: 2023-09-27 17:49:19

我有一个应用程序显示某人的图像在SkyD..哦OneDrive !

这是场景:从MainPage.xaml经过imageId到达ImagePage.xaml。然后从ImagePage.xaml内部深入到新的ImagePage.xaml,以此类推。

ImagePage.xaml有一个像这样的大图:

<Image Source="{Binding ImageUrl}" Stretch="Uniform" Margin="12"/>

问题是,当它深入时,在某个点达到内存限制并退出。

问题是,如何预防OutOfMemoryException ?我想了个办法在深入之前卸载页面。谢谢。

Update: from inside ImagePage:

NavigationService.Navigate(new Uri("/ImagePage.xaml?Id=" + id, UriKind.Relative));

如何防止OutOfMemoryException

导航到新页面时,前一个页面保留在内存中。如果你继续这样做,你最终会耗尽内存,就像你做的那样。

在你的情况下,我认为最好的解决方案是重新考虑你的页面流程。基本上,不是每次都导航到页面的新实例,而是停留在同一个页面并显示新图片。也要跟踪所要求的图片。这样,当用户按下后退键时,您就可以检查历史记录中是否有图片并将其显示回来,而不是返回到上一页。

总结一下,首先需要存储图片历史。对于这个目的,Stack是完美的:

private Stack<string> History { get; set; }

当您需要显示新图片时(您之前有一个imagpage .xaml导航),将之前的图片添加到历史记录中并显示新图片:

this.History.Push(oldPicture);
// Load the new picture

然后,在OnBackKeyPressed事件中,如果历史记录不是空的,取消导航。否则,检索最新条目并显示它:

protected override void OnBackKeyPress(CancelEventArgs e)
{
    if (this.History.Count > 0)
    {
        e.Cancel = true;
        var picture = this.History.Pop();
        // Display the picture
    }
}
相关文章:
  • 没有找到相关文章