Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to dispose resources in a System.Windows.Form-derived class?

Tags:

c#

idisposable

I've got a form that creates a couple of disposable resources in its constructor that I need to dispose of. However, the C# form designer already produces a Dispose() method in the Designer.cs file that doesn't appear to have any type of user hook in it. So I'm at a loss as to how I'm supposed to implement the typical IDisposable pattern.

This form is occasionally created but never shown, so using the Close event won't help.

The objects in question are not IComponents, so I can't just add them to this.components.

Where can I put this clean-up code and be sure it will run when the form is disposed?

like image 846
Michael Edenfield Avatar asked Jun 27 '11 22:06

Michael Edenfield


3 Answers

You can move the Dispose() method from the Designer.cs file to your source code file. And alter it to add dispose calls for any disposable members in your form class. This is one of the few cases where it is okay to edit the designer file, you only need to stay away from the code that inside the #region marked "Windows Form Designer generated code".

like image 58
Hans Passant Avatar answered Nov 11 '22 22:11

Hans Passant


I've often wondered about this though I never actually ran into an issue with it. You can use the Disposed event, although there might be a better way to hook into Dispose that I missed.

like image 41
configurator Avatar answered Nov 11 '22 22:11

configurator


Form and Control provide a "Disposed" event that may be used to dispose any resources they use.

like image 1
supercat Avatar answered Nov 11 '22 23:11

supercat