Remove Pages windows phone

后端 未结 1 913
离开以前
离开以前 2020-12-21 12:11

I have a big project where my application keeps retaining a page which I navigated away from. The page is only used minimal, and have a lot of graphics, I therefore want it

1条回答
  •  醉酒成梦
    2020-12-21 12:42

    The WP Silverlight runtime will keep up to three pages in memory, even after being removed from the backstack. The reason for this behavior is still unclear to me, but I've found a (ugly) workaround: http://blogs.codes-sources.com/kookiz/archive/2013/11/11/wpdev-give-that-memory-back.aspx

    Basically, override the OnNavigatedTo handler of your page, and force a garbage collection three times, separated by calls to the dispatcher:

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
    
        this.Dispatcher.BeginInvoke(() =>
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
    
            this.Dispatcher.BeginInvoke(() =>
            {
                GC.Collect();
                GC.WaitForPendingFinalizers();
    
                this.Dispatcher.BeginInvoke(() =>
                {
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                });
            });
        });
    }
    

    As crazy as it sounds, it works.


    In your case, you have another problem. You are keeping the page alive with your popup. Let me explain:

    In the CreatePopups method, you create the popup and add it to the grid of the starting page. In the popup, you start a timer to call UpdateMemoryInfo at regular interval. The timer is kept alive by the .NET runtime until it's stopped. The timer keeps a reference on your popup because you're using an instance method as event handler. Your popup is keeping a reference to the grid through the Parent property. The grid is keeping a reference to the page through its own Parent property. So you just made your page immortal, for as long as your timer is ticking. To prove that the issue is there, just make the UpdateMemoryInfo method static (and remove all the UI updating code there's inside). Since the event handler is now static, the timer won't hold a reference to instance of popup. Run the profiler, and you'll see that the instance of the page is now reclaimed by the garbage collector as you expect.


    Of course, it supposes that your pages have been removed from the back stack. Either by pressing the back key or calling the NavigationService.GoBack() method, or by manually removing them using NavigationService.RemoveBackEntry() (in case you only use forward navigation)

    0 讨论(0)
提交回复
热议问题