9

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

2

2 Answers 2

9

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.

2
2

I think Because the dispatcher timer has long life time than the page ,and a good habbit is stop or cancel the eventhandler, so the page has the memory leak.I studying the gc,it's a little diffcult topic.....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.