Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When does a PhoneApplicationPage get disposed?

For example, if I have a page like this:

public partial class Page1 : PhoneApplicationPage
{
    DispatcherTimer timer = new DispatcherTimer();

    public Page1()
    {
        InitializeComponent();

        timer.Interval = TimeSpan.FromSeconds(5);
        timer.Tick += new EventHandler(timer_Tick);
        timer.Start();
    }

    void timer_Tick(object sender, EventArgs e)
    {
         MessageBox.Show("timer tick"); 
    }
}

In the app, I navigate to this page, it will pop up a message box every 5 seconds. Then I press the "Back" button on the phone and navigate back to the previous page. But the weird thing is that it still pops up a message box every 5 seconds. I know I can stop the timer in the OnNavigatedFrom method, but why is this happening? Isn't a page disposed after you press the back button on it?

Thanks

like image 214
Cui Pengfei 崔鹏飞 Avatar asked Jul 20 '11 21:07

Cui Pengfei 崔鹏飞


1 Answers

It will get disposed by the GC when nothing is keeping it awake. This DispatcherTimer keeps it awake, even though it was created by the page. My guess in the past has been that the DispatcherTimer is being referenced by the Dispatcher itself, and so can't clean up, or something along those lines.

To demonstrate add a finalize method

#if DEBUG
  ~MyPage() {
    System.Diagnostics.Debug.WriteLine("Killing MyPage");
  }
#endif

Then add a button somewhere on the main page to force a GC.Collect()

If you shut down the timer in OnNavigatedFrom your page will get cleaned up, if you do not, it will not.

I haven't tested this yet with Mango to see if it is smarter, but with the 7.0 tools I had to do a bit of work to get around this.

like image 142
Chris Sainty Avatar answered Sep 23 '22 12:09

Chris Sainty