Cleaning objects off a form, Where and When?

2019-05-06 14:33发布

问题:

I have a simple Windows form application. On the form I have a custom class that has it's own Dispose method.

So the question is when should I call this?

Is the FormClosed event (i.e. Form1_FormClosed) the correct place to do this? Or should I be writing a custom Dispose method for the form?

For bonus points: Can a from be reopend once closed? (Obviously if it can then the FormClosed is the wrong way to go!)

Thanks.

回答1:

A wee bit of surgery is required. Open the node next to your form in the Solution Explorer window. Double-click the Designer.cs file for the form. Locate the Dispose() method and cut-and-paste it into your form's source code file. Now you can alter it and call the Dispose methods on the disposable object references in your form class.

Pre-empting: no, it is okay to edit this part of the designer file. Only the section in the #region is off limits.



回答2:

Controls that implement IDisposable should be added to the System.ComponentModel.IContainer components property of the form.

In the dispose of the form all disposables in that collection will be disposed of. (All puns intended)

EDIT To see this just drop a Timer on the form and have a look at the generated code.



回答3:

If you have reason then on form closing you should verify bool Application.IsExiting.

If you want not to destroy form then on form closing cancel closing and do Hide(). Then form can be reopened using Show(). The whole form state will remain the same.



回答4:

Never call dispose if you don't have a really good reason for doing so.

If the object contains an heavy object (Image, database connection etc) call a close as soon as you're done with it.

Calling a dispose on a close forces you to reload the resource on an open. A form can be reopened if you don't destroy any important items after closing it and keep a reference.

By 'definition' close does the same thing as 'dispose' (and it closes windows/forms). Every close call in the .net framework just calls dispose internally anayway.

@comment

I've used an application that kept around 40MB bitmaps. Calling dispose on those really helped on the memory bound machine. Calling dispose on objects with the information given in the question is impossible. Calling it 'just because' is bad, calling it because the designer does it is even worse.