Cleaning objects off a form, Where and When?

好久不见. 提交于 2019-12-05 16:56:57

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.

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.

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.

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!