为什么Dispose被调用?
在我的应用程序中,我看到有时我的主窗体上的Dispose方法显然没有理由被调用。我没有通过UI关闭应用程序,我没有发送关闭窗口消息或在任何地方调用Close(),但Dispose方法仍然被调用。以下是调用堆栈:为什么Dispose被调用?
Bitter.Shell.exe!Bitter.Shell.MainForm.Dispose(bool disposing = true) Line 853 C#
System.dll!System.ComponentModel.Component.Dispose() + 0x12 bytes
System.Windows.Forms.dll!System.Windows.Forms.ApplicationContext.Dispose(bool disposing) + 0x35 bytes
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.DisposeThreadWindows() + 0x33 bytes
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.Dispose(bool postQuit) + 0xf8 bytes
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(int reason = -1, System.Windows.Forms.ApplicationContext context = {System.Windows.Forms.ApplicationContext}) + 0x276 bytes
System.Windows.Forms.dll!System.Windows.Forms.Application.ThreadContext.RunMessageLoop(int reason, System.Windows.Forms.ApplicationContext context) + 0x61 bytes
System.Windows.Forms.dll!System.Windows.Forms.Application.Run(System.Windows.Forms.Form mainForm) + 0x31 bytes
Bitter.Shell.exe!Bitter.Shell.Program.Main() Line 105 + 0x26 bytes C#
如果内存不足以尝试清理,CLR会调用它吗?我知道Windows Mobile可以做到这一点,但并不认为这发生在桌面世界。任何人都知道为什么这会被称为?
编辑:重新启动后,我不再看到这个问题。所以它似乎是由于当时我的系统状态。无论哪种方式,原因应该仍然是可以识别的。
是否在UI线程中抛出异常?
我不这么认为。我在Program.cs中有一个try catch块,它捕获任何不会被别处捕获的东西,通常会捕获这些东西。 – 2009-09-11 16:21:31
但是在Dispose被调用之后,它会捕获它......如果你在Dispose中打入调试器,它将有机会抓住它。 – 2009-09-11 17:10:19
在你的dispose方法中添加一个断点,并按照调用堆栈查看代码调用dispose方法的内容。除非您的应用程序正在被系统或程序本身关闭,否则.NET不会随时调用dispose。
必须抛出异常。你是否嵌套消息循环?
问题中显示了callstack。 – 2009-09-11 16:20:32
您确定您的表单不是以某种方式关闭吗?
编辑:单击调试,异常,使VS在所有托管的异常中断,并查看是否有任何异常被吞下。
在Jon Skeet的回复评论中提及的Program.cs中的Application.Run尝试/捕获不会捕获所有异常。
我建议你调用Application.Run前添加一个处理Application.ThreadException:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.ThreadException += new ThreadExceptionEventHandler(Application_ThreadException);
try
{
...
Application.Run(new MainForm());
}
catch (Exception ex)
{
... handle exception ...
}
}
private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
{
... handle exception ...
}
Program.Main的内容并不重要 - 这是从Application.Run到来。 – SLaks 2009-09-11 16:08:06
是的,但我有围绕Program.Main Application.Run try/catch。 – 2009-09-11 17:06:04
你发现了吗? – Psddp 2017-01-14 00:06:11