Do I need to dispose of dynamically-created controls before exiting a form?

社会主义新天地 提交于 2019-12-08 09:56:43

问题


I've created a new instance of my options form with the using directive, so it is disposed of automatically when I'm finished with it. Do I need to dispose of the dynamically-created controls on the form before closing it, or will they be automatically disposed of when I call this.Close()?


回答1:


Generally no, all controls are dynamically created. Usually in the InitializeComponent() method, it isn't fundamentally different when the code appears somewhere else. Dynamically removing controls is what can get you into trouble.

Controls are automatically disposed when their Parent is disposed. So as long as you have them added to their parent through its Collection property then you don't need extra code to dispose. The trigger is closing the window for a form that's displayed with the Show() method, the using statement in your code for a form that's displayed with ShowDialog().

You can check that you got it right by using Task Manager. Add the USER Objects column with View + Select Columns (right-click the listview header in Windows 8). The counter is very reliable. Repeatedly creating and closing your form must not constantly increase the displayed value.

Leaking USER Objects is a very common bug in Winforms, the garbage collector does not keep you out of trouble. Always be very wary of any ControlCollection.Clear() or Remove/At() statement in your code.



来源:https://stackoverflow.com/questions/24350844/do-i-need-to-dispose-of-dynamically-created-controls-before-exiting-a-form

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