If I have a form that owns managed IDisposable objects that need to stay around for the lifetime of the form (i.e. class level members, perhaps a class the wraps and manages a timer for the sake of unit testing), when should I call Dispose() on them?
For the sake of the question (to avoid “GC will dispose it for you” type of answers), let’s also assume there is additional shutdown logic I need to call, for example:
Buffer.Flush()
Buffer.Dispose()
I could put it in the existing implementation of the Dispose() method in my partial class (Form.Designer.vb), but modifying that class is typically frowned upon.
It seems that the FormClosed or Disposed events would be the best choice. Any reason to chose one over the other?
The “proper” way is to move the Dispose() method from the form’s Designer.vb file to the form’s source code file and edit it. That’s however awkward in the vb.net IDE, it hides that file. You’d have to click the Show All Files icon to see it.
Using FormClosed is wrong, that will dispose your objects too early when your form is displayed with ShowDialog(). Which may cause ObjectDisposed exceptions when you retrieve the dialog results.
Using the Disposed event is fine.