本文介绍了using语句围绕对话的形式,以确保垃圾收集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个Windows窗体应用程序包含了数以千计的形式。

We have a Windows Forms application that contains thousands of forms.

许多都是暂时显示为通过ShowDialog的()方法的对话框。

Many of these are temporarily displayed as dialogs via the ShowDialog() method.

这个应用程序已经问世多年,我们已经发现,许多的形式没有得到垃圾收集及时,由于形式不同的资源泄漏或控制它使用。

This application has been around for years and we've discovered that many of the forms are not getting garbage collected in a timely manner due to various resource leaks in the form or the controls that it uses.

这是没有被妥善处理,但可能还有其他类型的资源泄漏尚未被定性GDI +资源特别是,我们发现的例子。

Specifically, we've found examples of GDI+ resources that aren't being disposed of properly, although there may be other types of resource leaks that have not yet been characterized.

虽然解决这个正确的方法显然是要经过各种形式和每一个控制和消除所有的资源问题。这需要一定的时间来完成。

Although the right way to resolve this is obviously to go through every form and every control and eliminate all of the resource problems. This will take some time to accomplish.

作为短期替代方案中,我们已发现,在表格上明确地调用Dispose()似乎发起垃圾收集过程和形式及其资源被立即释放。

As an short term alternative, we have found that explicitly calling Dispose() on the form seems to initiate the garbage collection process and the form and its resources are deallocated immediately.

我的问题是,是否将是一个合理的解决办法来包装每个窗体的ShowDialog的()块using语句,这样的Dispose() ?一直形式显示出来后调用,也将本是一般要建立一个很好的做法。

My question is whether is would be a reasonable workaround to wrap each form's ShowDialog() block in a using statement so that Dispose() is called after the form has been displayed, and also would this be a good practice to institute in general?

例如,现有的代码从:

public void ShowMyForm()
{
    MyForm myForm = new MyForm();
    myForm.ShowDialog();
}

要这样:

public void ShowMyForm()
{
    using (MyForm myForm = new MyForm())
    {
        myForm.ShowDialog();
    }
}

在我们的测试中,MyForm的的Dispose()方法从未得到要求第一个例子,但它被立刻要求第二个例子。

In our testing, MyForm's Dispose() method never gets called for the first example, but it gets called immediately for the second example.

这看起来像一个合理的方法作为短期解决办法,而我们花时间追踪每个特定资源的问题?

Does this seem like a reasonable approach as a short term workaround while we spend the time tracking down each of the specific resource issues?

是我们可以考虑一个短期的解决方法还有其他方法和/或方法进行识别和解决这些类型的资源问题?

Are there other approaches that we could consider for a short term workaround and/or methodologies for identifying and resolving these types of resource issues?

推荐答案

据的,必须显式调用Dispose使用ShowDialog的显示形式(不像Show方法):

According to MSDN, you must explicitly call Dispose on forms shown using ShowDialog (unlike with the Show method):

在一个表格显示为一个模式对话框,单击关闭
按钮
导致窗体被隐藏,DialogResult属性(与窗体的右上角的X键可设置)
到DialogResult.Cancel。不同于非模态形式,该关闭的方法是不是由.NET Framework称为
当用户点击对话框的形式接近
键或设置DialogResult属性的值。
相反的形式被隐藏,可以再次显示而不创建
中的对话框的新实例。因为形式显示一个对话框,
框是隐藏的,而不是封闭的,则必须调用
,当你的应用程序不再需要表格形式的Dispose方法。

这篇关于using语句围绕对话的形式,以确保垃圾收集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 06:55