I would like to write the following code in c#. a) small console application that simulates memory leak. b) small console application that would invoke the above application and
In a Console or Win app create a Panel
object(panel1) and then add 1000 PictureBox
having its Image
property set then call panel1.Controls.Clear
. All PictureBox controls are still in the memory and no way GC
can collect them:
var panel1 = new Panel();
var image = Image.FromFile("image/heavy.png");
for(var i = 0; i < 1000;++i){
panel1.Controls.Add(new PictureBox(){Image = image});
}
panel1.Controls.Clear(); // => Memory Leak!
The correct way of doing it would be
for (int i = panel1.Controls.Count-1; i >= 0; --i)
panel1.Controls[i].Dispose();
Memory leaks in calling Controls.Clear()
Calling the Clear method does not remove control handles from memory. You must explicitly call the Dispose method to avoid memory leaks