Proper cleanup of WPF user controls Proper cleanup of WPF user controls wpf wpf

Proper cleanup of WPF user controls


I'm afraid that Dispatcher.ShutdownStarted really does seem to be the only mechanism WPF provides for disposing of resources in UserControls. (See a very similar question I asked a while ago).

Another way to approach the problem is to move all of your disposable resources (if at all possible) out of the code behind and into separate classes (such as the ViewModel when using the MVVM pattern). Then at a higher level you could handle your main window closing and notify all the ViewModels via a Messenger class.

I am surprised you don't get the Dispatcher.ShutdownStarted event. Are your UserControls attached to the top-level window at the time?


The IDisposable interface has (almost) no meaning under WPF, because the mechanism is different from Winforms. In WPF, you must bear in mind the visual and logical tree: that's fundamental.
So, any visual object generally lives as child of some other object. The base of the WPF building mechanism is to attach the visual object hierarchically, then detach and destroy when they aren't useful.

I think you may check the OnVisualParentChanged method exposed since the UIElement: this method is called either when a visual object is attached and when is detached. That could be the right place to dispose the unmanaged objects (sockets, files, etc).


I was looking for this too and after testing differents options I implemented the solution of venezia

protected override void OnVisualParentChanged(DependencyObject oldParent)    {        if (oldParent != null)        {            MyOwnDisposeMethod(); //Release all resources here        }        base.OnVisualParentChanged(oldParent);    }

I realized that when parent call Children.Clear() Method and had already items added to Children, DependencyObject had a value. But when parent added an item (Children.Add(CustomControl)) and children was empty DependencyObject was null.