I read that WP7 uses backstack to represent the back navigation of the application.
In my application, there are 2 pages
timer1's callback in page1 is used to log count1++ value
timer2's callback in page2 is used to log count2++ value.
Question 1 In page 1, I start timer1, then navigate to page2.
I thought page1 is pushed to the backstack and it is deactive. But the timer1 still runs with count1 incremented ??
Question 2 In page2, I start timer2 and back to page1.
I thought page2 is dispose. But the timer2 still runs with count2 incremented?
The page may not be in view, but it is still running - just not drawing onto the screen. Any variables you have will still exist when you return to the page. Similarly, anything like a DispatcherTimer, will continue to exist, and continue to tick until you stop it.
An immediate issue is if you aren't saving a reference to your timer - if you don't, you won't be able to stop it! anyway, something like this would work:
protected void override OnNavigatedFrom(Object sender, NavigationEventArgs e){
if (myTimer != null){ timer.Stop();}
e.OnNavigatedFrom(sender,e);
}
protected void override OnNavigatedTo(Object sender, NavigationEventArgs e){
//create, or turn on your timer, etc.
e.OnNavigatedTo(sender,e);
}
The idea is basically how you describe: When leaving the page, 'pause' the timer. When you come back, turn the timer back on.
For Question 2:
When you create a timer, the variable to it may be local, but the event
created from the timer is global - you will need to dispose
of it when you're done with it. And that means not not only stopping it, but removing the event itself -
myTimer.Tick -= onTimerTick; // where onTimerTick is the name of your Event
Finally,
When your app gets Deactivated
, your timer is stopped and killed. You should make sure to restart / recreate any timers that you have for when this happens. And if you're keeping count of something, remember to store the count so that you can keep track of where the user left off.