Disposing WPF UserControl

Topics: Prism v2 - WPF 4
Jun 4, 2013 at 4:45 PM
I am using Prism with MEF bootstrapper and MVVM design pattern.

I have a TabControl and I am creating a new scoped region manager for every tabItem which holds the same usercontrol (which has nested regions in it): regionManager.Regions["TAB_REGION"].Add(theView, null, true);

[I am not assigning any variable to the new scoped regionmanager. Also, theView is NonShared and is created for each tabItem and contains some regions Also theView has prism:ClearChildViewsRegionBehavior.ClearChildViews="True"].

Using ViewModel-First approach, when I remove a TabItem from the TabControl, I call a CloseThisViewModel() method on my theViewModel:

public void CloseThisViewModel(){
        this._theView = null;
and in theView:

public void CloseThisView(){
        this.DataContext = null;
I manually call GarbageCollector:
I have a destructor/Finalizer in my ViewModel and this.Dispatcher.ShutdownStarted in my View. I do not have any unmanaged code in my View.

I observe that TheViewModel destructor is called after closing the tabItem.
Dispatcher.ShutdownStarted is only called when main application exits.
Could anyone provide inputs on the following:

Since I open/close many tabitems, I want to ensure that the unused usercontrols (my views) are not floating/dangling around. I know that corresponding viewmodels are properly disposed off. Also, I don't intend to close my main application ever.
Can there be a memory leak?
Is there a way to call Dispatcher.ShutdownStarted from outside UI Thread?
How can I verify, before application exits, that the view with a null reference are garbage collected?
Please let me know if I could provide more information.

Any help is highly appreciated.
Jun 4, 2013 at 7:58 PM

First of all, if there is no strong reference that is pointing to your views, then there should be no memory leaks as they would be garbage-collected when needed.

Based on my understanding, the ShotdownStarted event is invoked when the corresponding Dispatcher of the thread is closed (which usually happens when the thread finished its execution.) Hence, this event should not be used to detect when the components are being disposed and neither should be fired manually. Regarding this same subject, I believe you might find the following threads in the MSDN forums interesting:
Also, based on my understanding, when an application exits, all it's resources included the memory allocated is releases, so it doesn't seem to be necessary to check if a view was garbage-collected a this point.


Damian Cherubini
Jun 7, 2013 at 7:57 PM
Thanks Damian.

This resolves my concerns regarding the memory leaks and disposing WPF controls.