37

AppDomain.UnhandledException と Application.DispatcherUnhandledException の違いに関するいくつかの優れた投稿を読んだ後、両方を処理する必要があるようです。これは、ユーザーがメイン UI スレッドによってスローされた例外 (つまり、Application.DispatcherUnhandledException) から回復できる可能性が非常に高いためです。正しい?

また、両方のプログラム、または Application.DispatcherUnhandledException のみのプログラムを続行する機会をユーザーに与える必要がありますか?

以下のコード例は、AppDomain.UnhandledException と Application.DispatcherUnhandledException の両方を処理し、例外が発生しても続行するオプションをユーザーに提供します。

[ありがとう、以下のコードの一部は他の回答から持ち上げられています]

App.xaml

<Application x:Class="MyProgram.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         Startup="App_StartupUriEventHandler"
         Exit="App_ExitEventHandler"
         DispatcherUnhandledException="AppUI_DispatcherUnhandledException">
    <Application.Resources>
    </Application.Resources>
</Application>

App.xaml.cs [編集済み]

/// <summary>
/// Add dispatcher for Appdomain.UnhandledException
/// </summary>
public App()
    : base()
{
    this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
}

/// <summary>
/// Catch unhandled exceptions thrown on the main UI thread and allow 
/// option for user to continue program. 
/// The OnDispatcherUnhandledException method below for AppDomain.UnhandledException will handle all other exceptions thrown by any thread.
/// </summary>
void AppUI_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
    if (e.Exception == null)
    {
        Application.Current.Shutdown();
        return;
    }
    string errorMessage = string.Format("An application error occurred. If this error occurs again there seems to be a serious bug in the application, and you better close it.\n\nError:{0}\n\nDo you want to continue?\n(if you click Yes you will continue with your work, if you click No the application will close)", e.Exception.Message);
    //insert code to log exception here
    if (MessageBox.Show(errorMessage, "Application User Interface Error", MessageBoxButton.YesNoCancel, MessageBoxImage.Error) == MessageBoxResult.No)
    {
        if (MessageBox.Show("WARNING: The application will close. Any changes will not be saved!\nDo you really want to close it?", "Close the application!", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
        {
            Application.Current.Shutdown();
        }
    }
    e.Handled = true;
}

/// <summary>
/// Catch unhandled exceptions not thrown by the main UI thread.
/// The above AppUI_DispatcherUnhandledException method for DispatcherUnhandledException will only handle exceptions thrown by the main UI thread. 
/// Unhandled exceptions caught by this method typically terminate the runtime.
/// </summary>
void OnDispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
    string errorMessage = string.Format("An application error occurred. If this error occurs again there seems to be a serious bug in the application, and you better close it.\n\nError:{0}\n\nDo you want to continue?\n(if you click Yes you will continue with your work, if you click No the application will close)", e.Exception.Message);
    //insert code to log exception here
    if (MessageBox.Show(errorMessage, "Application UnhandledException Error", MessageBoxButton.YesNoCancel, MessageBoxImage.Error) == MessageBoxResult.No)
    {
        if (MessageBox.Show("WARNING: The application will close. Any changes will not be saved!\nDo you really want to close it?", "Close the application!", MessageBoxButton.YesNoCancel, MessageBoxImage.Warning) == MessageBoxResult.Yes)
        {
            Application.Current.Shutdown();
        }
    }
    e.Handled = true;
}
4

2 に答える 2

41
  • AppDomain.CurrentDomain.UnhandledException理論的には、appdomain のすべてのスレッドですべての例外をキャッチします。ただし、これは非常に信頼できないことがわかりました。
  • Application.Current.DispatcherUnhandledExceptionUI スレッドですべての例外をキャッチします。これは確実に機能するようで、UI スレッドのハンドラーを置き換えAppDomain.CurrentDomain.UnhandledExceptionます (優先されます)。e.Handled = trueアプリケーションの実行を維持するために使用します。

  • 他のスレッドで例外をキャッチする場合 (最良の場合、それらは独自のスレッドで処理されます)、System.Threading.Tasks.Task (.NET 4.0 以降のみ) のメンテナンスが少ないことがわかりました。メソッドでタスクの例外を処理し.ContinueWith(...,TaskContinuationOptions.OnlyOnFaulted)ます。詳細については、こちらの回答を参照してください。

于 2012-10-22T14:37:50.767 に答える
5

AppDomain.UnhandledExceptionハンドラーは次 のように配線されます。

AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

しかし、ハンドラーで処理されたものとしてフラグを立てる方法を見つけることができませんでした。そのため、これにより、何をしてもアプリがシャットダウンするように見えます。ですから、これはあまり役に立たないと思います。

最初の接続時とまったく同じように、プロキシを再初期化するだけで回復できるため、処理Application.Current.DispatcherUnhandledExceptionとテストを行う方が適切です。CommunicationObjectFaultedException例えば:

void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e) {
    if (e.Exception is CommunicationObjectFaultedException) { //|| e.Exception is InvalidOperationException) {
        Reconnect();
        e.Handled = true;
    }
    else {
        MessageBox.Show(string.Format("An unexpected error has occured:\n{0}.\nThe application will close.", e.Exception));
        Application.Current.Shutdown();
    }
}

public bool Reconnect() {
    bool ok = false;
    MessageBoxResult result = MessageBox.Show("The connection to the server has been lost.  Try to reconnect?", "Connection lost", MessageBoxButton.YesNo);
    if (result == MessageBoxResult.Yes)
        ok = Initialize();
    if (!ok)
        Application.Current.Shutdown();
}

ここで、Initializeには初期プロキシインスタンス化/接続コードがあります。

上記で投稿したコードでは、ハンドラーをxamlとコードで配線することでDispatcherUnhandledException 2回処理していると思われます。

于 2012-04-08T08:47:21.543 に答える