我正在使用普通的threads
實現的項目。應用程序中的大多數預期異常都會被處理,但是,有些線程會引發意外的異常並導致應用程序崩潰(應用程序同時基於I/O
和Client-Server
,因此實際上不可能處理所有異常)。在線程中拋出未處理的異常不會被捕獲
爲了解決這個問題,我試圖定義一個全局的UnhandledExceptionHandler
,以便應用程序顯示一個友好的消息而不是崩潰。這是我試過的:
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException +=
new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
// The rest of the startup logic goes here
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Utilities.DisplayUnhandledException((Exception)e.ExceptionObject);
}
}
雖然這不起作用。 CurrentDomain_UnhandledException
永遠不會被調用。不幸的是,我無法改變應用程序的結構,這意味着我無法使用任務並行庫。我無法弄清楚爲什麼這不起作用。有沒有其他方法來處理線程中拋出的異常?任何幫助表示讚賞。
嘗試'Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);'和'Application.ThreadException + = Application_ThreadException;' – Blorgbeard
這裏有一些徹底的解釋:http://stackoverflow.com/questions/1472498/wpf-global-exception-handler –