处理所有子控件和数据 - C# [英] Disposing All Child Controls and Data - C#

查看:30
本文介绍了处理所有子控件和数据 - C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在面板中加载了一个用户控件,用户控件本身包含很多内部控件,例如标签页、面板、按钮,并且在其面板内还会有一些其他用户控件.

I Load a User Control inside a panel, the user Control itself contains so many inner controls such as tab pages, panels, buttons and also inside its panels there will be some other user controls.

假设我在 MainPanel 内加载主用户控件,如果我使用它:

Let say I Load the Main User Control inside the MainPanel, If I use this:

MainPanel.Controls.Clear();

它不会清除内存,所以我用它来代替:

It will not clear the memory, so I use this instead:

while (MainPanel.Controls.Count > 0) MainPanel.Controls[0].Dispose();

但它似乎会处理主用户控件并稍微清除内存,我认为该用户控件中的所有控件仍然存在于内存中.如何递归遍历所有内部控件并一一处置?

But it seems it will Dispose the Main User Control and will clear memory just a little and I think all controls inside this user control still exist in the memory. How can I iterate recursively through all of the inner controls and dispose them one by one?

此外,在用户控件内部,有几个加载一些数据的网格控件.它们不绑定到任何数据库,只是通过 LINQ 从数据库和 new 命令中获取一些数据.是否需要在处置控件之前销毁这些数据,否则它们会被控件处置从内存中删除?

Furthermore, inside the user control, there are several grid controls that load some data. They are not binding to any database, just fetching some data by LINQ from the database and new command. Do I need to destroy those data before disposing the control or they will be deleted from memory by control disposing?

推荐答案

https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/unmanaged?view=netframework-4.8

使用完组件后调用 Dispose.Dispose 方法使组件处于不可用状态.调用 Dispose 后,您必须释放对 Component 的所有引用,以便垃圾收集器可以回收 Component 占用的内存.有关详细信息,请参阅清理非托管资源和实施处置方法.

Call Dispose when you are finished using the Component. The Dispose method leaves the Component in an unusable state. After calling Dispose, you must release all references to the Component so the garbage collector can reclaim the memory that the Component was occupying. For more information, see Cleaning Up Unmanaged Resources and Implementing a Dispose Method.

for (int i = MainPanel.Controls.Count - 1; i >= 0; i--) { 
    MainPanel.Controls[i].Dispose();
}

您不需要取消引用任何其他数据.只有控件才能被 gc 选中.

You don't need to dereference any other data. Only the controls so that they can be picked up by gc.

请记住,如果您取消引用具有 ObjectB 的 ControlA,那么 ObjectB 也会取消引用并且可以被拾取.

Bear in mind that if you dereference ControlA which has ObjectB, then ObjectB is also dereferenced and can be picked up.

这篇关于处理所有子控件和数据 - C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆