Removing Delegates in Dispose method

G

Guest

I have several bound controls which attach delegates to a data source. I have
code in the control's Dispose override to remove the delgates.

I'm finding that when the form is closed, the control's Dispose method is
not getting called and the delegate is not getting detached. I tried
overriding the form's Dispose method, and calling Dispose on each control,
but it's not getting called either.

If I call form.Dispose on exit from ShowDialog, I get an
ObjectDisposedException on the the Controls collection.

My question is twofold: 1) is Dispose the correct place to remove delgates?
And 2) where would be the best/safest place to put my call to form.Dispose?
 
T

Tomer Gabel

Hello david,

Forms derive from Controls which are Components. Those in turn implement
IDisposable, so what you're doing simply won't work (why you can derive and
reimplement IDisposable is a mystery to me, although I imagine that what
actually happens is that you're simply hiding the base IDisposable implementation).

One way to resolve this is to add an event handler to the Form.Disposed event
and handle it there. As for it being the safest place, it depends on the
logic behind your delegates (when/why are they being registered), but it
basically seems like a reasonable location for such code.

Regards,
Tomer Gabel (http://www.tomergabel.com)
Monfort Software Engineering Ltd. (http://www.monfort.co.il)
 
F

Fabien

Hi,

Ok with you, but destructors (or finalizers) are invoked automatically
and can't be invoked explicitly by the garbage collector. The C#
destructor is simply a shortcut for declaring a Finalize method that
chains up to its base class. In the case of David, I agree with you,
he must explicitly call the Dispose method.

BR

Fabien Decret
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top