c# : simulate memory leaks

后端 未结 7 867
囚心锁ツ
囚心锁ツ 2021-02-05 17:26

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

7条回答
  •  不思量自难忘°
    2021-02-05 18:15

    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

提交回复
热议问题