Navigating to page increases memory usage Windows Universal 8.1

时光毁灭记忆、已成空白 提交于 2019-12-12 13:17:48

问题


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



来源:https://stackoverflow.com/questions/24307375/navigating-to-page-increases-memory-usage-windows-universal-8-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!