MVVM Light Toolkit でビルドされた WPF アプリケーションで単純なグローバル例外ハンドラーを作成しようとしていますが、それを機能させるのに苦労しています。
問題は、次のように Dispatcher と AppDomain の両方にリスナーを登録しても、ビュー モデルで発生した例外がアプリの UnhandledException ハンドラーでキャッチされないことです。
private void Application_Startup(object sender, StartupEventArgs e)
{
AppDomain.CurrentDomain.UnhandledException += DomainUnhandledException;
DispatcherUnhandledException += App_DispatcherUnhandledException;
}
private void DomainUnhandledException(object sender, UnhandledExceptionEventArgs unhandledExceptionEventArgs)
{
var exception = unhandledExceptionEventArgs.ExceptionObject as Exception;
ShowExceptionMessage(exception);
}
private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
ShowExceptionMessage(e.Exception);
e.Handled = true;
}
ビューモデル用に切り取られたこのコードで説明されている解決策とともに、問題のスポットを説明しているこのブログ投稿を見つけました。
// Throw the exception in the UI thread.
App.Current.RootVisual.Dispatcher.BeginInvoke(() => { throw new MyException(); });
ただし、VM で自分自身をスローする例外だけでなく、すべての例外をグローバル例外ハンドラーにバブルアップさせたいと考えています。
問題は、他のスレッドからの例外を 1 か所で UI スレッドに再スローすることはどうにかして可能かということです。
更新: アプリのイベント ハンドラーのセットアップのためのより詳細なコードを追加しました。