问题描述
我正在创建Windows Universal 8.1应用程序.每次我导航到一个页面,然后又导航回该页面,然后再次导航到该页面时,该页面的新实例将保存在内存中.显然,垃圾收集器会在一段时间后释放内存,但是如果不需要,我宁愿不使用该内存.有没有办法回收或处理这些页面?
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?
推荐答案
在Windows Uriversal App中,我们可以使用 NavigationCacheMode 来recycle
页面.可以在页面的构造函数中设置它.例如,有一个我们要回收的MainPage:
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;
}
设置后,我们无需重新创建即可返回MainPage.
After setting it, We can go back to MainPage without re-create it.
如果NavigationCacheMode设置为已禁用.页面的内存从其 OnNavigatedFrom 时将被释放.
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
这篇关于导航到页面会增加内存使用率Windows Universal 8.1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!