How to force Universal Application to release memory?

By : O.O
Source: Stackoverflow.com
Question!

Created a simple app that leaks memory:

View

<Page
   ...
    x:Class="App3.MainPage"
    mc:Ignorable="d">
    <StackPanel>
        <Image Width="300" Height="200" 
            Source="/Assets/BBlHOiv.jpg"></Image>
        <Button Click="Button_Click">Navigate</Button>
    </StackPanel>
</Page>

Code Behind

public sealed partial class MainPage : Page
{
    public MainPage()
    {
        this.InitializeComponent();            
    }

    private void Button_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
    {
        this.Frame.Navigate(typeof(MainPage));
    }

Every time the button is clicked, the code navigates to the same page which has an image on it ~400KB. If I continue to click the button at a quick pace, the memory rises each click, or ever few clicks. The memory is not reclaimed, or at least not in a timely manner. In a real app, with more complex pages and more complex navigation (including circular navigation) this can be become a big problem. Question is, how to force the app to release the memory? Ideally, once a page is no longer needed/shown.

I've tried the following things with no luck.

#1 Clearing the frame's navigation stack

    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        base.OnNavigatedFrom(e);
        this.Frame.BackStack.Clear();
    }

#2 When using MVVM, setting the DataContext to null (when datacontext is set in the XAML markup)

    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        base.OnNavigatedFrom(e);
        this.DataContext = null;
        this.Frame.BackStack.Clear();
    }
By : O.O


Answers

The garbage collector in .Net does it at it's own pace and not necessarily when things are closed. I don't recommend doing this, but you can manually call GC.Collect();. I would track down the source of the "leak".

More information on the garbage collection process: By : Rick Burns



This video can help you solving your question :)
By: admin