Clearing controls from FlowLayoutPanel not calling destructors?

六月ゝ 毕业季﹏ 提交于 2019-12-21 17:27:42

问题


Sorry if I'm missing something obvious, but I'm trying to clear the controls (a series of user controls) from a FlowLayoutPanel - (panelName).Controls.Clear();. Unfortunately this doesn't seem to be calling the destructors for the objects on the panel - the User Objects column in the task manager just keeps going up and up, until it hits 10,000 and throws an excecption.

Does anyone know what I'm missing here?


回答1:


Not a solution, but a workaround - the objects do seem to be destroyed by this (rough, from memory) code:

while(FlowLayoutPanel.Controls.Count > 0)
     FlowLayoutPanel.Controls.Remove(0);



回答2:


eftpotrm's workaround above still kept the user handles count growing for me, however, if you just manually dispose after removing the control, that fixed it 100% for me.

while (myFlowLayoutPanel.Controls.Count > 0)
{
     var controltoremove = myFlowLayoutPanel.Controls[0];
     myFlowLayoutPanel.Controls.Remove(controltoremove);
     controltoremove.Dispose();
}



回答3:


.NET does not have the concept of destructors. .NET has something called "finalizers" which look syntactically like destructors in C#. For more information, check out Jeff Richter's awesome book on how the CLR works -- CLR via C#.

You may want the objects to implement the IDisposable pattern, and then call their Dispose() method when you're done with them.




回答4:


Try using a memory profiler, (e.g. ants) it will tell you what is keeping the control alive. Trying to 2nd guess this type of problem is very hard.

Red-gate gives 14 days tail that should be more then enough time to tack down this problem and decide if a memory profiler provides you with long term value.

There are lots of other memory profilers on the market (e.g. .NET Memory Profiler) most of them have free trials, however I have found that the Red-Gate tools are easy to use, so tend try them first.



来源:https://stackoverflow.com/questions/1378668/clearing-controls-from-flowlayoutpanel-not-calling-destructors

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