Form.ShowDialog()并处理 [英] Form.ShowDialog() and dispose

查看:100
本文介绍了Form.ShowDialog()并处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的方法:

public void Show()
{
   Form1 f = new Form1();
   f.ShowDialog();
}

我是否仍需要致电处置表单,即使它超出范围,也可以进行垃圾收集。

Do I still need to call dispose on the form even though it will go out of scope, which will be eligible for garbage collection.

经过一些测试,多次调用了Show()..在某些时候,好像GC收集了它,因为我可以看到内存峰值,然后它下降到某个时间点。

From some testing, calling this Show() multiple times .. at some point it seems like the GC collects it since I can see the memory spiking then it goes down at some point in time.

从MSDN看来,当不再需要该表单时,您必须调用dispose。

From MSDN it seems to say you MUST call dispose when the form is not needed anymore.

推荐答案

在您的特定示例中,不,它不太有用。表单不会占用大量资源,因此,如果清理它的一部分代码花费的时间更长,则不会造成问题。如果这种形式恰好是用于播放视频的控件,那么也许它实际上是在占用大量资源,并且如果您确实在dispose方法中处理了这些资源,那是值得的花时间打电话处理。不过,对于您99%的表单,其Dispose方法将为空,无论您是否调用它,都不会对程序产生任何(或任何明显的)影响。

In your specific example, no, it's unlikely that it would be particularly useful. Forms do not hold onto a significant amount of resources, so if it takes a little bit longer for some portion of it's code to get cleaned up it isn't going to cause a problem. If that form just happens to be holding onto a control that is used to, say, play a video, then maybe it's actually holding onto some significant number of resources, and if you actually do dispose of those resources in the dispose method then it's worth taking the time to call dispose. For 99% of your forms though, their Dispose method will be empty, and whether you call it or not is unlikely to have any (or any noticeable) effect on your program.

之所以存在它,主要是因为它能够在重要的那1%的情况下处理资源。

The reason that it's there is primarily to enable the ability to dispose of resources in those 1% of cases where it's important.

Form 已关闭,其 Dispose 方法已被调用。如果您要在此之前处理Forms资源,则只需要使用添加或显式 Dispose 调用即可。表格已关闭。 (这对我来说似乎是一个坏主意)。这很容易测试。只需使用两种形式创建一个项目。让第二种形式将事件处理程序附加到 Dispose 事件并显示消息框或类似内容。然后,当您创建该表单的实例并显示它(是否显示为对话框时)时,您会看到,即使将 Form实例保留在周围并且没有您,关闭它时,消息框也会立即弹出。曾经需要使用 Dispose 调用添加。

It's also worth noting that when a Form is closed its Dispose method is already being called. You would only ever need to add a using or explicit Dispose call if you want to dispose of a Forms resources before that form is closed. (That sounds like a generally bad idea to me). This is easy enough to test. Just create a project with two forms. Have the second form attach an event handler to the Disposing event and show a message box or something. Then when you create an instance of that form and show it (as a dialog or not) you'll see that when you close it the message box will pop up right away, even if you keep the 'Form' instance around and without you ever needing to add a using or Dispose call.

这篇关于Form.ShowDialog()并处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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