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

筅森魡賤 提交于 2019-12-21 06:26:13

问题


In a previous question about ridding the system tray of an old NotifyIcon I was told that I should Dispose anything that implements IDisposable. Sounds like good practise to me however as a newbie it raises more questions :-)

How do I know if a control implements IDisposable?

Should I build a class that attempts to dispose everything on all my forms in the formclosed event?

Something like this?(psuedocode):

foreach(control cont in form)  
{  
try{cont.Dispose()}  
catch{}  
}

If not, then how do I know what controls I would need to manually dispose, or should I simply watch for unusual behaviour during testing?

G

EDIT:So when I click the big red "X" on my child form, that doesn't cause it to Dispose? is that right? What is the reason for this?


回答1:


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).




回答2:


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.




回答3:


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

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



回答4:


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



来源:https://stackoverflow.com/questions/615466/when-should-i-manually-dispose-of-controls-how-do-i-know-if-a-control-implement

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