In my Xamarin app, I have Five pages, Page 1, Page 2, Page 3, Page 4 and Page 5. When navigating from Page 5 to Page 3, I called Navigation.RemovePage() to remove Page 4 in NavigationStack. However, there is huge memory leak when calling RemovePage(). I want to know if there is any workaround to avoid memory leak when trying to remove the page between two pages in the NavigationStack? (Since Page 3 is not the Root Page, so I can't use PopToRootAsync())
Also, anyone can explains me why using PushModalAsync() will remove all pages in NavigationStack and only leaves the current added page and in both NavigationStack and ModalStack.
Thank you very much.
In Xamarin, how to avoid memory leak when using Navigation.RemovePage()
During testing, it will not leak memory when the RemovePage
method is called.
private void Button_Clicked(object sender, EventArgs e)
{
Navigation.RemovePage( Navigation.NavigationStack.Where(a=> a is Page4).FirstOrDefault());
}
anyone can explains me why using PushModalAsync() will remove all pages in
NavigationStack
and only leaves the current added page and in both NavigationStack and ModalStack.
The matched with PushModalAsync
navigation behavior in UWP platform is showing a ContentDialog
. And it will not effect NavigationStack
The following is the test code.
private void PushClick(object sender, EventArgs e)
{
Navigation.PushModalAsync(new MainPage());
foreach (var item in Navigation.NavigationStack)
{
System.Diagnostics.Debug.WriteLine(item.GetType().Name);
}
}
For complete code sample please refer this link.
A simple test to check if your app leaks memory might be helpful. Enforce garbage collection after the operation you are investigating. Understanding how the .net garbage collector works might also be helpful link. Look at the memory consumption before you remove the page and after. For test purposes force garbage collection right after the page is removed
private void Button_Clicked(object sender, EventArgs e)
{
Navigation.RemovePage( Navigation.NavigationStack.Where(a=> a is Page4).FirstOrDefault());
GC.Collect(2, GCCollectionMode.Forced);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With