Trying to replace Controls.Clear() to avoid memory

2020-02-16 03:13发布

I replaced:

panel.Controls.Clear();

with:

Clear(panel);

Where:

public static void Clear(Control ctrl)
{
    while (ctrl.Controls.Count > 0) ctrl.Controls[0].Dispose();
}

And I get the following error: at Application.Run(new Form1()); System.ObjectDisposedException was unhandled Cannot access a disposed object. Object name: 'Label'.

Any idea why that might be?

Thanks.

EDIT: See How to Clear() controls without causing a memory leak

EDIT: Sorry, I’m probably disposing of something which I just want to remove from its parent. I’ll check that. Thanks for the answers.

3条回答
贪生不怕死
2楼-- · 2020-02-16 03:45

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

查看更多
倾城 Initia
3楼-- · 2020-02-16 03:49

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();
}
查看更多
神经病院院长
4楼-- · 2020-02-16 04:00

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.

查看更多
登录 后发表回答