4

I've got two pages in my Xamarin Forms app, and I'm trying to do basic navigation:

public partial class Page1
{
   void OnAddButtonClicked (object sender, EventArgs args)
   { Navigation.PushAsync (new Page2 ()); }
}

public partial class Page2
{
   ~Page2()
   { Debug.WriteLine ("Page2.~Page2()"); }
   protected override void OnAppearing ()
   { Debug.WriteLine ("Page2.OnAppearing()"); }
   protected override void OnDisappearing ()
   { Debug.WriteLine ("Page2.OnDisappearing()"); }
}

public class App : Application
{
   public App()
   {
      MainPage = new NavigationPage(new Page1());
   }
}

When I click on the button, the second page appears as desired, and when I click either back button (the OS back button or the left-arrow in the title bar) it does return to the first page but what is concerning me is that my second page is never destructed. I realize the garbage collector runs whenever it darn well pleases, but I can switch between pages multiple times (creating a new Page2 each time) and sit without touching the app for minutes and none of the Page2 objects are ever destructed.

The official documentation doesn't say anything about destructing old pages, but there is another thread on stackoverflow that implies I am responsible for the lifetimes of my pages. So what's my final answer - do I need to manually destruct my pages, or will Xamarin eventually take care of that for me?

Community
  • 1
  • 1
Betty Crokker
  • 3,001
  • 6
  • 34
  • 68
  • 1
    Your `Page2` should eventually be destroyed, assuming you have no other references to it out there. It is possible to inadvertently create extra references, especially with events. I'd say to try forcing the GC to run, with `GC.Collect()` (a few times) and see if your `Page2` gets destroyed. With just 2 pages, it will take a long time actually create any pressure on memory. – dylansturg Aug 26 '16 at 15:40
  • In my Page1, I added code so that when I press a button, it calls GC.Collect() three times, followed by GC.WaitForPendingFinalizers(). The destructor for my Page2 didn't get called. However, when I pressed the button a second time, it did finally call the destructor for my Page2. So I guess the answer is that my Page2 is correctly getting marked for deletion, and I don't have to worry about calling RemovePage() or other shenanigans. – Betty Crokker Aug 26 '16 at 19:48
  • Yeah - getting the GC to collect an object is a little tricky. It takes a few passes (I won't get into how/why). Xamarin's profiler tool can be helpful for finding memory leaks too, but it's a little unstable. – dylansturg Aug 26 '16 at 19:57
  • 1
    For me, I'm not worried about forcing the garbage collection, as long as I know it's eventually going to happen. – Betty Crokker Aug 26 '16 at 20:20

0 Answers0