Dispose Resources when navigate

Topics: Prism v4 - WPF 4
Aug 1, 2011 at 1:07 PM
Edited Aug 1, 2011 at 1:15 PM

Hello.

I use the MVVM-Pattern for my Views. In my ViewModel i start a DispatcherTimer in the constructor.

When i navigate to another View via the Prism RegionManager.RequestNavigate-Method i want to remove the DispatcherTimer to avoid memory leaks.

I implement IDisposable. In the Dispose-Method i stop the DispatcherTimer and set it null.

 

I'm not sure if that is the right way. The Dispose-Method is called then i navigate to another View but when i Navigate back to this View via the RegionManager.RequestNavigate-Method i don't know where i have to instanziate the DispatcherTimer again.

Developer
Aug 1, 2011 at 7:53 PM

Hi Steve,

You can implement the interface INavigationAware in the ViewModel that your View uses, so that it is notificated when a navigation event takes place.

Basically, the INavigationAware interface exposes two methods that are called during a navigation operation:

  • OnNavigatedFrom, which is called before navigation takes place, when the active view is navigated away to another one,
  •  And OnNavigatedTo, which is called after navigation is complete, when the view is navigated into from another one.

In this case, you can start the DispatcherTimer in the OnNavigatedTo method and remove it in the OnNavigatedFrom method.

You can find more information about this in the section View and View Model Participation in Navigation of Chapter 8: Navigation of the Prism documentation.

I hope you find this helpful.

Guido Leandro Maliandi
http://blogs.southworks.net/gmaliandi

Aug 1, 2011 at 8:04 PM

Thanks for your fast answer.

Do i understand it right that i don't need to set the timer null?

Developer
Aug 2, 2011 at 1:42 PM

Hi,

Based on my understanding of your scenario, in order to avoid memory leaks you could unhook from the events of the Timer, and set it to null, and then instantiate it and hook to its events again in the OnNavigatedTo method.

In case you unhook from the events, it's possbile that you don't need to set the timer to null.

I hope you find this helpful.

Guido Leandro Maliandi
http://blogs.southworks.net/gmaliandi