2016-07-12 34 views
0

非常に大きなC#アプリケーションで作業します。大きすぎるので、未処理の例外をすべてキャッチできません。C#UnhandledExceptionウィンドウから終了するときにアプリケーションが終了しないようにする

このアプリケーションには、「あなたは終了してもよろしいですか?アプリケーションのFormClosingイベントでメッセージがポップアップ表示されます。

未処理の例外が実行されると、ユーザーは終了ボタンをクリックすることがあります。私はこれがApplication.Exit()または何らかのフォームを呼び出すと信じています。これはまた、FormClosingイベントとポップアップウィンドウをトリガします。この時点で

Sample Unhandled exception dialog box

あなたがポップアップで[はい]をクリックしますか、何かどうかは関係しません。 Application.Exit()のために応答が受信された後、アプリケーションは終了します。

Application.Exit()が呼び出されないようにする方法はありますか?

+3

ハンドル'UnhandledException'イベントが発生するので、ダイアログを完全に置き換えることができます。 – SLaks

+0

あなたのコードは何ですか?あなたのコーディングスタイルを知らなくても、あなたの答えを提案するにはどうすればいいですか? – mostafa8026

+1

どのようにして基本的なエラー処理を省略して大きなアプリケーションを作成できましたか? –

答えて

1

アプリケーションが終了しないようにする必要がある場合は、例外を処理する必要があります。 try..catchを例外をスローする可能性があるすべての場所に持たせることは妥当です(多数存在してはいけません)。しかし、そのためのグローバルなイベントがあります。

メインスレッドで例外が処理し、AppDomainの未処理の例外に伝播されていない場合は、アプリが有効な状態ではない、それはterminateに持っています。最後に、例外情報を記録し、アプリケーションが正常終了する前に保存できるものを保存しようとします。

あなたが処理されない例外を記録し、ユーザーフレンドリーなエラーを示すために、このイベントをサブスクライブする必要があります。

static void Main() 
{ 
    AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; 

    Application.EnableVisualStyles(); 
    Application.SetCompatibleTextRenderingDefault(false); 
    Application.Run(new Form1()); 
} 

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) 
{ 
    // we can log info from e.ExceptionObject and check e.IsTerminating 
} 

In the .NET Framework versions 1.0 and 1.1, an unhandled exception that occurs in a thread other than the main application thread is caught by the runtime and therefore does not cause the application to terminate. Thus, it is possible for the UnhandledException event to be raised without the application terminating. Starting with the .NET Framework version 2.0, this backstop for unhandled exceptions in child threads was removed, because the cumulative effect of such silent failures included performance degradation, corrupted data, and lockups, all of which were difficult to debug. For more information, including a list of cases in which the runtime does not terminate, see Exceptions in Managed Threads .

あなたはまた、処理する必要があります。

Application.ThreadException += Application_ThreadException; 
関連する問題