Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory is not being freed automatically in windows phone 8

I am currently working in windows phone 8. I am facing some memory related problems.

Let I have two PhoneApplicationPages. Both pages contain images, text-blocks etc. Suppose when I am in page-1 my app is using 30MB of memory. If I navigate from page-1 to page-2 the amount of used memory increased to 35MB. Then when I go back to page-1, the used memory is still 35MB.

Why memory or cache is not being freed automatically? Is there any way to clear memory or cache manually?

(p.s: both of the classes that are representing the pages are static and I am setting them to null in OnNavigatedFrom method.)

like image 718
raisul Avatar asked Mar 18 '23 23:03

raisul


1 Answers

For some reasons I'm unaware of, the runtime keeps a reference to your page for a while, even after the page has been removed from the back stack. I've documented my findings on this behavior here: http://blogs.codes-sources.com/kookiz/archive/2013/11/11/wpdev-give-that-memory-back.aspx

Long story short, add this code to your pages if you want to reclaim the memory immediately:

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();
            });
        });
    });
}

Note that it's not really a leak, even if you don't use this code your memory will eventually get released (typically after about three page navigations). But freeing the memory earlier can really help for memory-intensive applications.

like image 131
Kevin Gosse Avatar answered Apr 02 '23 03:04

Kevin Gosse