我有一个WPF桌面应用程序,可以调用后台线程中的任务,如下所示:
private async void SomeButton_Click(object sender, EventArgs e)
{
await Task.Run(async () =>
{
await DoSomething();
});
}
public async Task DoSomething()
{
//do something that throws an exception, mocked like this
throw new Exception("Test");
}
我在App启动中有顶级异常处理程序,如下所示:
this.Dispatcher.UnhandledException += OnDispatcherUnhandledException;
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
这些处理程序都只是将异常记录到文件中。
如果我将DoSomething
的全部内容放在try / catch块中,catch将起作用并且Task完成。
但是如果抛出的异常不在try / catch中,则调用CurrentDomain_UnhandledException
处理程序,但IsTerminating
属性为true且应用程序崩溃。
如何设置一个全局异常处理程序来处理异常而不会使我的进程崩溃,而不必在非Dispatcher线程上调用的每个方法中放置try / catch处理?
在OnDispatcherUnhandledException
事件处理程序中,您应该将Handled
属性设置为true
。
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
// log
e.Handled = true;
}