When should I manually dispose of controls? How do I know if a control implements IDisposable?

一个人想着一个人 提交于 2019-12-03 22:28:10

Any control that is owned by the form is disposed of when the form is disposed of. In other words, when calling Dispose(), a control will call Dispose() on all of its children. Note that hiding a form will not call Dispose(), but in most cases it's fine to just create a dialog and dispose of it as needed.

This is always the case for designer-generated forms and controls. If you create a non-visual component like NotifyIcon in code (without setting the owner), you have to manually dispose of it. But it's usually easier to set the owner properly.

Any class implementing IDisposable should call Dispose() on its childs, no matter if in a collection or in a property, unless there's a good reason not to (i.e. in some cases the caller might stay the owner of an object - but that's exactly where the concept of setting the ownership is for).

One option is to run FxCop over your assemblies. One of its rules will verify that Dispose is being called on all objects that implement IDisposable, and warn you if you have violations.

EDIT: To answer your later question, Dispose is not automatically called. You need to handle that yourself. Here is one article on the subject.

You could verify with the is operator, that a object is implementing IDisposable:

if(object is IDisposable) {
    ((IDisposable)object).Dispose();
}

If you hit X to close a modal form, the form is actually hidden. You have to manually call dispose to release the resource.
See here: http://msdn.microsoft.com/en-us/library/system.windows.forms.form.dialogresult.aspx

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