Clearing controls from FlowLayoutPanel not calling

2020-07-17 04:10发布

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?

4条回答
贼婆χ
2楼-- · 2020-07-17 04:38

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);
查看更多
ゆ 、 Hurt°
3楼-- · 2020-07-17 04:41

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();
}
查看更多
ゆ 、 Hurt°
4楼-- · 2020-07-17 04:45

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

查看更多
\"骚年 ilove
5楼-- · 2020-07-17 04:52

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.

查看更多
登录 后发表回答