I am really curious to get to know how to clear/releaase/dispose a page properly. Many answers were given such as
You do not, the garbage collector does it for you when appropriate.
How to dispose current page in UWP
foreach(var item in rootFrame.BackStack.ToList()) rootFrame.BackStack.Remove(item)
Also, to minimize the memory allocation, you must override method
OnNavigatedTo
andOnNavigatedFrom
.In
OnNavigatedTo
method:
- Instantiate all memory intensive object or resources
- Add all events handlers you need
- starts all timers, tasks or threads
In
OnNavigatedFrom
:
- Dispose all resources
- Stops all timers, tasks or threads
- Remove references from all heavy objects
- Remove all events handlers
- Only if you really need, call GC.Collect() ove all events handlers Only if
you really need, call GC.Collect()
UWP Windows 10 App memory increasing on navigation
So, in our current project, I´ve just made a test to find out how I can "release" ressources. The short answer is... I couldn´t.
I´ve set the NavigationCacheMode to disabled on purpose.
protected override void OnNavigatedFrom(NavigationEventArgs e) {
((ActivityViewModel)this.DataContext).OnDestroy();
this.DataContext = null;
base.OnNavigatedFrom(e);
}
I´ve actively called the OnDestroy method to my viewmodel (which is absolutely not great), to set heavy objects to null and release events
public void OnDestroy() {
this.ActivitySource.FetchRows -= this.ActivitySource_FetchRows;
this.ActivitySource.GetUniqueValues -= this.ActivitySource_GetUniqueValues;
this.TaskObjectSource = null;
this.UnitOfWork.Dispose();
this.ActivitySource = null;
this.NavigateToTaskCommand = null;
this.SelectedItem = null;
}
Guess what. Each time I´ve reentered the page, the ram will slightly increase. If you would repeat this for x times, your application will unevitable throw OutOfMemoryException.
So I was thinking about this and came up with the conclusion that a page is just a control container and should be cached, whereas your datacontext holds the data information which drives the ui controls through its bindings. In the end, it makes most sense to me. Why do create a new instance of a page when you can just exchange its datacontext or manipulate properties in its given context. But then, why is the default NavigationCacheMode 'Disabled'? How would Dialogs be managed due to its volatile behavior? The more I think about this, the more questions I have.
How does "the big guys" dealing with this "issue"? Maybe my understanding is wrong, but then there might be sources to get knowledge. From my current perspective, I really enjoy coding with the uwp. But sometimes it makes me feel like certain things are not well optimized or missing (On-Premise Active Directory :/ ).
If you need additional Information, or even a reproduced sample, feel free to ask.
Thank you in advance.
Best regards