全局异常处理程序可以处理等待函数中的异常吗?

问题描述 投票:0回答:1

我有一个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处理?

.net wpf multithreading exception-handling
1个回答
0
投票

OnDispatcherUnhandledException事件处理程序中,您应该将Handled属性设置为true

private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
   // log
   e.Handled = true;
}
© www.soinside.com 2019 - 2024. All rights reserved.