tags:

views:

4180

answers:

4

I have created a custom WPF user control which is intended to be used by a third party. My control has a private member which is disposable, and I would like to ensure that its dispose method will always get called once the containing window/application is closed. However, UserControl is not disposable. I tried implementing the IDisposable interface and subscribing to the Unloaded event but neither get called when the host application closes. If at all possible, I don't want to rely on consumers of my control remembering to call a specific Dispose method.

 public partial class MyWpfControl : UserControl
 {
     SomeDisposableObject x;

     // where does this code go?
     void Somewhere() 
     {
         if (x != null)
         {
             x.Dispose();
             x = null;
         }

     }
 }

The only solution I have found so far is to subscribe to the Dispatcher's ShutdownStarted event. Is this a reasonable approach?

this.Dispatcher.ShutdownStarted += Dispatcher_ShutdownStarted;
+6  A: 

Interesting blog post here:

http://geekswithblogs.net/cskardon/archive/2008/06/23/dispose-of-a-wpf-usercontrol-ish.aspx

It mentions subscribing to Dispatcher_ShutDownStarted to dispose of your resources.

Ray Booysen
well I was hoping there would be a cleaner way than this, but it looks like for now this is the best to do it.
Mark Heath
But what if the UserControl dies before the app dies? The Dispatcher will only shyt down when the app does, right?
Robert Jeppesen
A: 

How about using a Finalizer and calling your Dispose method from there?

Patrick Klug
A: 

An UserControl has a Destructor, why don't you use that?

~MyWpfControl()
 {
  // Dispose of any Disposable items here
 }
This doesn't seem to work. I just tried that approach and it never gets called.
JasonD
+3  A: 

You have to be careful using the destructor. This will get called on the GC Finalizer thread. In some cases the resources that your freeing may not like being released on a different thread from the one they were created on.

Ade Miller