如何确保Winform被垃圾收集? [英] How do I make sure a winform is garbage collected?
问题描述
正如我从在线实验和个人实验中学到的那样,GC永远不会调用表单的终结器(System.Windows.Forms.Form). 据说在表格GC.的Dispose()中调用了SuppressFinalize(),以便不再调用finalizer.
As I learned from online and my personal experiment, the finalizer of a form (System.Windows.Forms.Form) never gets called by GC. It is said that inside the Dispose() of Form GC.SuppressFinalize() is called so that finalizer wouldn't gets called again.
示例:
public partial class UpdateForm : Form
{
public UpdateForm()
{
InitializeComponent();
// Listen to the event of some model
Database.OnDataUpdated += new EventHandler(DataBase_OnDataUpdated);
}
~UpdateForm()
{
// Never gets called.
}
private void DataBase_OnDataUpdated(object sender, EventArgs e)
{
// Update data on this form
}
}
但是,如上面的示例所示,如果表单连接(+ =)某个模型的事件并且不断开(-=)Dispose()中的事件,则即使该表单永远也不会被垃圾回收,即使Dispose()被调用.
However, as the example above shows, if the form connects(+=) a event of some model and doesn't disconnect(-=) the event in Dispose(), the form would never be garbage collected, even if the Dispose() gets called.
我要检查表单是否真的被垃圾回收了是,我在表单内部创建了一个大数组,以消耗大量内存,如下所示:
What I do to check if the form is really garbage collected is that I create a big array inside the form to consume a lot of memory as below:
int[] dummyArray = new int[1024 * 1024 * 128]; // Comsume 128MB memory
然后,我查看Windows中任务管理器的内存配置文件,以查看在处理完表单后调用GC.Collect()时是否减少了内存使用.
Then I look at the Memory Profile of Task Manager in Windows to see if the memory usage is reduced when I call GC.Collect() after the form is disposed.
我的方法并不聪明,我想知道是否还有其他更聪明的方法或一些工具来确认表单实际上是垃圾收集?谢谢.
My method is not smart, and I wonder if there is other smarter way or some tools to confirm the form is actually garbage collected? Thanks.
推荐答案
您可以使用弱引用不会阻止对象被垃圾回收,您可以使用该属性来检查对象是否存在:
A weak reference does not prevent the object from being garbage collected, and you can use that property to check if it has been:
if (weakref.IsAlive) { /* not yet garbage collected */ }
该表单不需要终结器即可工作.
The form does not need a finalizer for this to work.
这篇关于如何确保Winform被垃圾收集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!