小编Kyl*_*yle的帖子

应该同时使用AppDomain.UnhandledException和Application.DispatcherUnhandledException吗?

在阅读了一些关于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>
Run Code Online (Sandbox Code Playgroud)

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)
{ …
Run Code Online (Sandbox Code Playgroud)

c# wpf exception-handling uncaught-exception uncaughtexceptionhandler

32
推荐指数
2
解决办法
2万
查看次数