Trying to replace Controls.Clear() to avoid memory leak doesn’t work – why?

前端 未结 3 1488
攒了一身酷
攒了一身酷 2020-12-22 07:35

I replaced:

panel.Controls.Clear();

with:

Clear(panel);

Where:

public static void Clear(C         


        
相关标签:
3条回答
  • 2020-12-22 08:18

    I was probably disposing of some Controls I was using later on in the code.

    0 讨论(0)
  • 2020-12-22 08:20

    Dispose() has nothing to do with memory under normal circumstances. It doesn't release memory, it doesn't remove the object from a collection, and it doesn't invoke the garbage collector. Instead, the purpose of .Dispose() is to clean up non-memory resources: database connections, sockets, device handles, gdi handles, etc.

    The only way this could possible help you fix a memory issue is if you're using custom controls that each rely on code in an unmanaged (non-.Net) dll.

    0 讨论(0)
  • 2020-12-22 08:27

    You need remove controls you disposed, but there might be a better approach:

    public static void Clear(Control ctrl)
    {
        foreach(Control c in ctrl.Controls) c.Dispose();
        ctrl.Controls.Clear();
    }
    
    0 讨论(0)
提交回复
热议问题