locked
How to Dispose an obsolete page, when navigating to a new page?? RRS feed

  • Question

  • Hi

    Step 1)I have two pages, from Page1, I am navigating to page 2 with NavigationService.Navigate(new Uri("/Pages/Page2.xaml", UriKind.Relative));
    in the page2 constructor I am subscribing to an event from a different framework, 
    Step 2)after I'm done with work on page2 I'm navigating back to page1 or with NavigationService.GoBack(); or with the Back button.

    When after these two steps you repeat them again, the following problem will occur:

    The event will trigger as many times as we have called page2, its because we create a new instance every time we call NavigationService.Navigate(new Uri("/Pages/Page2.xaml", UriKind.Relative));, I could unsubscribe from the event every time I'm navigating away from page2, but even still the different instances of page 2 will remain in the background...

    How can I dispose of them so that they don't take away system resources, I don't know much how the garbage collector works here, but I don't want to wait ages till it removes those pages.

    I hope someone can help me on this issue.
    Friday, June 17, 2011 12:30 PM

All replies

  • Actually, if you want your page to be disposed by the garbage collector, you have to unsubscribe from the event.

    When subscribing to the event from the other framework, you're giving a reference to your page. When the garbage collector is triggered, it detects that an "active" object (the framework) holds a reference to your page, and thus your page is considered as "still active" and won't be disposed. It can be avoided by using weak references when implementing the event, but it's rarely done, and from the behavior of your app it seems that the framework didn't.

    You can also create global context class which will subscribe to the event, then forward it to your pages using a weakreference-based system. But that's probably overkill, unsubscribing from the event is way easier.
    Friday, June 17, 2011 1:10 PM
  • Thank you for the quick reply.
    I'll just unsubscribe from the event on the NavigatedFrom event, and Subscribe to the events on the NavigatedTo event.

    Best Regards
    Friday, June 17, 2011 1:48 PM