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
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.
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