Navigating to page increases memory usage Windows

2019-07-01 18:19发布

问题:

I'm creating a Windows Universal 8.1 application. Everytime I navigate to a page and then navigate back and then to the page again a new instance of the page is being held in memory. Obviously the garbage collector frees the memory after a while, however I'd rather not use the memory if it's unneeded. Is there a way to recycle or dispose of these pages?

回答1:

In Windows Uriversal App, We can use NavigationCacheMode to recycle a page. It can be set in the constructor of the page. For example, there is a MainPage we want to recycle:

public MainPage()
{
    this.InitializeComponent();

    // Set the NavigationCacheMode of Page to Enabled. 
    // The page is cached, but the cached instance is discarded when the size 
    //     of the cache for the frame is exceeded.
    this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;

    // OR Set the NavigationCacheMode of Page to Required. 
    // The page is cached and the cached instance is reused for every visit 
    //     regardless of the cache size for the frame.
    // this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Required;
}

After setting it, We can go back to MainPage without re-create it.

If NavigationCacheMode is set to Disabled. The memory of page will be released when OnNavigatedFrom from it.

There is a similar question as SO: Page constructor gets called again when navigating back in Windows 8 C# App