WinForms-何时调用Dispose?什么时候隐式? [英] WinForms - when to call Dispose? When is it implicit?

查看:47
本文介绍了WinForms-何时调用Dispose?什么时候隐式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用.NET MemoryProfiler查找我的应用程序中的内存泄漏,而在创建和显示Winform时,我似乎无法弄清楚何时应该调用Dispose()的模式.看来,当我这样做

I was using .NET MemoryProfiler to look for memory leaks in my app and I can't seem to figure out the pattern of when I should call Dispose() when it comes to creating and showing winforms. It seems that when I do

Form frm = new SomeForm();
frm.ShowDialog();
bool test = frm.IsDisposed()

test是"False",这令我感到惊讶,.NET MemoryProfiler还确认未正确处理该表格.我以为如果我关闭(X)"对话框,它将在表单上有效地调用.Dispose(),但事实并非如此.我很好奇,如果我这样做:

test is "False" which is surprising to me and .NET MemoryProfiler also confirms that the form wasn't disposed of properly. I thought if I "Close (X)" the dialog then it would effectively call .Dispose() on the form but doesn't seem to be the case. I am curious what would happen if I do:

Form frm = new SomeForm();
frm.Show();

当我单击表单上的关闭(X)"按钮时,该表单会被丢弃吗?我试图找到一条规则,何时应该调用"Dispose()",何时不需要调用"Dispose"(因为它将被隐式处置)...

Would the form be disposed when I click the "Close (X)" button on the form? I am trying to find a rule when I should call "Dispose()" and when I don't need to call "Dispose" (because it will be disposed implicitly)...

推荐答案

来自

如果使用Show方法显示表单,则将自动调用Dispose.如果使用了ShowDialog之类的其他方法,或者根本没有显示该窗体,则必须在应用程序中调用Dispose.

Dispose will be called automatically if the form is shown using the Show method. If another method such as ShowDialog is used, or the form is never shown at all, you must call Dispose yourself within your application.

这篇关于WinForms-何时调用Dispose?什么时候隐式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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