尝试替换 Controls.Clear() 以避免内存泄漏不起作用 –为什么?
我将: 替换
panel.Controls.Clear();
为:
Clear(panel);
其中:
public static void Clear(Control ctrl)
{
while (ctrl.Controls.Count > 0) ctrl.Controls[0].Dispose();
}
我收到以下错误: at Application.Run(new Form1());
System.ObjectDisposeException 未处理 无法访问已处置的对象。 对象名称:“标签”。
知道为什么会这样吗?
谢谢。
编辑: 请参阅如何在不导致内存泄漏的情况下 Clear() 控件
编辑:抱歉,我可能正在处理一些我只想从其父级中删除的东西。我会检查一下。感谢您的回答。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正常情况下,
Dispose()
与内存无关。它不会释放内存,不会从集合中删除对象,也不会调用垃圾收集器。相反,.Dispose()
的目的是清理非内存资源:数据库连接、套接字、设备句柄、gdi 句柄等。这是唯一的方法如果您使用的自定义控件都依赖于非托管(非 .Net)dll 中的代码,则可能有助于解决内存问题。
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.
您需要删除您处置的控件,但可能有更好的方法:
You need remove controls you disposed, but there might be a better approach:
我可能正在处理我稍后在代码中使用的一些
Control
。I was probably disposing of some
Control
s I was using later on in the code.