Disposing dynamically created controls

北战南征 提交于 2019-12-07 14:28:13

问题


I have a WinForms TabControl that I am dynamically adding TabPages to at runtime. Each TabPage contains a WebBrowser control. I also have the ability to remove the TabPages at runtime.

Should I bother Dispose()ing the TabPage and/or WebBrowser controls?

It seems to me I should at least Dispose() the WebBrowser control since it is a bit of a resource hog.


回答1:


You should Dispose() your tab page when you remove it. This will automatically dispose all of the child controls.

For details, see the Control.Dispose documentation:

Releases the unmanaged resources used by the Control and its child controls and optionally releases the managed resources.

The tab page's dispose will also dispose of all of the children controls for you.




回答2:


Everything you allocate that implements IDisposable should have Dispose called on it. That's the purpose of implementing IDisposable.




回答3:


If you explicitly call Dispose(), it will generally be cleaned up faster than if you don't. If you are concerned about resources, or your objects are holding onto other resources that might be scarce or in high demand, it's always a good idea to call Dispose() explicitly.

I always recommend this CodeProject article to help people understand the Dispose pattern properly, and what Dispose is all about. http://www.codeproject.com/KB/cs/idisposable.aspx



来源:https://stackoverflow.com/questions/1106549/disposing-dynamically-created-controls

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