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?
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".
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.
Form and Control provide a "Disposed" event that may be used to dispose any resources they use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With