Created a simple application 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 for
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)); }
Each time the button is pressed, the code goes to the same page with the image on it ~ 400 KB. If I continue to press the button quickly, the memory rises for every click or a few clicks. Memory is not being restored, or at least not in a timely manner. In a real application with more complex pages and more complex navigation (including circular navigation) this can be a big problem. The question is how to make the application free memory? Ideally, when the page is no longer needed / shown.
I tried the following things with no luck.
# 1 Clear frame 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 the datacontext is set in the XAML markup)
protected override void OnNavigatedFrom(NavigationEventArgs e) { base.OnNavigatedFrom(e); this.DataContext = null; this.Frame.BackStack.Clear(); }
source share