Windows Form FlowLayoutPanel Memory Leak ?

Published on Tuesday, November 20, 2012

There were not only one time, and there were lots of programmer who used Windows Form FlowLayoutPanel control got the memory leak issues.

In our case, we used FlowLayoutPanel control wrapped multiple user controls which include PictureBox controls and other controls. we need constantly clear the FlowLayoutPanel and add new user controls. We found the memory leak, looks like the FlowLayoutPanel did not “clear”, finally we found when we load FlowLayoutPanel clear method, the user controls seems still in the memory (with PictureBox maybe).

So we tried the manually load Dispose method before clear. like the following:

foreach (Control ctrl in flowlayoutpanal1.Controls)
 {
        ctrl.Dispose();  

 }

flowlayoutpanal1.Controls.Clear();

Also, we added other code in User Control's dispose method to dispose any 3rd party controllers which are not Microsoft Windows Form controllers.

However, we found the memory leak issue still there, we did not fix it.

Actually, in above code, we made a classic .NET error: when control disposed, it also was removed from its parent control. so the children controls of flowlayoutpanel1 always changed. so we should not use “foreach” for a changed list.

So now you know how you should dispose the children controls, the following is a sample, use For loop, and NOT from beginning, but from end of the list:

for(int i = flowlayoutpanel1.Controls.Count-1; i >= 0; --i)
{ 
   var ctl = flowlayoutpanel1.Controls[i];
    ctl.Dispose();
}