开发者

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()
    {
        InitializeCo开发者_Python百科mponent();

        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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜