2009-09-11 177 views
2

在我的應用程序中,我看到有時我的主窗體上的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可以做到這一點,但並不認爲這發生在桌面世界。任何人都知道爲什麼這會被稱爲?

編輯:重新啓動後,我不再看到這個問題。所以它似乎是由於當時我的系統狀態。無論哪種方式,原因應該仍然是可以識別的。

+0

Program.Main的內容並不重要 - 這是從Application.Run到來。 – SLaks 2009-09-11 16:08:06

+0

是的,但我有圍繞Program.Main Application.Run try/catch。 – 2009-09-11 17:06:04

+0

你發現了嗎? – Psddp 2017-01-14 00:06:11

回答

2

是否在UI線程中拋出異常?

+0

我不這麼認爲。我在Program.cs中有一個try catch塊,它捕獲任何不會被別處捕獲的東西,通常會捕獲這些東西。 – 2009-09-11 16:21:31

+1

但是在Dispose被調用之後,它會捕獲它......如果你在Dispose中打入調試器,它將有機會抓住它。 – 2009-09-11 17:10:19

2

在你的dispose方法中添加一個斷點,並按照調用堆棧查看代碼調用dispose方法的內容。除非您的應用程序正在被系統或程序本身關閉,否則.NET不會隨時調用dispose。

必須拋出異常。你是否嵌套消息循環?

+0

問題中顯示了callstack。 – 2009-09-11 16:20:32

2

您確定您的表單不是以某種方式關閉嗎?

編輯:單擊調試,異常,使VS在所有託管的異常中斷,並查看是否有任何異常被吞下。

1

在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 ... 
} 
相關問題