Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disposing a non-component when a form disposes?

I have a form that has a member that implements IDisposable but not IComponent. I need to dispose it when the form disposes. Unfortunately the form's dispose is already implemented in the automatically generated portion of the code, and is not partial.

How can I dispose this object?

like image 390
C. Ross Avatar asked Sep 30 '10 16:09

C. Ross


2 Answers

Override Form.Dispose(bool) in your form, and dispose of your object there.

In order to understand how this works, you can refer to MSDN's page on Implementing a Dispose Method. The Form class follows this pattern, which allows you to override Dispose(bool) in subclasses. (Just make sure to call base.Dispose(disposing) correctly in your override, as well.)


If you aren't comfortable moving this from the .designer.cs file into your main .cs file, the other option is to subscribe to your own FormClosed event, and dispose of your resources in that event handler. MSDN recommends this approach - from the docs for FormClosed:

You can use this event to perform tasks such as freeing resources used by the form and to save information entered in the form or to update its parent form.

like image 60
Reed Copsey Avatar answered Oct 01 '22 09:10

Reed Copsey


You can move the overridden Dispose(bool) method to your side of the partial class. From experience, it does not get recreated in the designer part.

like image 33
Henk Holterman Avatar answered Oct 01 '22 07:10

Henk Holterman