首页 > 解决方案 > UWP navigation memory leak

问题描述

We have noticed that our UWP apps have memory leaks. I have investigated it and found out that when navigating to new pages, the memory gets higher and doesn't seem to go down by much even when GC runs.

I have put together a small repro that consists of two pages:

  1. MainPage
<Page>
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="70" />
            <RowDefinition  />
        </Grid.RowDefinitions>

        <Button x:Name="navigateButton" Content="Navigate" HorizontalAlignment="Center"
                    Click="NavigateButton_Click" />

        <Frame x:Name="mainFrame" IsNavigationStackEnabled="False"
               Padding="10" Grid.Row="1" />
    </Grid>
</Page>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private void NavigateButton_Click(object sender, RoutedEventArgs e)
        {
            mainFrame.Navigate(typeof(Page1), null, new Windows.UI.Xaml.Media.Animation.DrillInNavigationTransitionInfo());
        }
    }
  1. Page1:
<Page>
    <VariableSizedWrapGrid ItemWidth="100" ItemHeight="60">
        <Button Padding="20, 10" Content="Hello!"/>
        <Button Padding="20, 10" Content="Hello!"/>
        <Button Padding="20, 10" Content="Hello!"/>
        <Button Padding="20, 10" Content="Hello!"/>
        <Button Padding="20, 10" Content="Hello!"/>

        <!-- And 25 more buttons here -->
    </VariableSizedWrapGrid>
</Page>
    public sealed partial class Page1 : Page
    {
        public Page1()
        {
            this.InitializeComponent();
        }

        ~Page1()
        {
            Debug.WriteLine("Page dead :(");
        }
    }

The full source code is available on GitHub.

And you can see a video of the repro.

I have also tried out setting Frame.IsNavigationStackEnabled to false, it doesn't help.

What am I doing wrong here?

An image of memory use after clicking on the Navigate button for a while

标签: c#memory-leaksuwpnavigation

解决方案


我使用的是 Windows 1803,因为我没有最新的 1809,但我认为它的工作原理相同,

在第 1 页的代码中:

 protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        base.OnNavigatedFrom(e);

        System.GC.Collect();
    }

这是检查应用程序是否必须处理页面的另一种方法。它有效。


推荐阅读