AppDomain.CurrentDomain.UnhandledException无法在异步方法中捕获异常

时间:2020-05-03 14:49:55

标签: c# unhandled-exception

MSDN开始:

如果在默认应用程序中处理了UnhandledException事件 域,在该域​​中针对 any 线程中的 any 未处理的异常, 无论线程从哪个应用程序域开始。

所以我有以下内容:

类中的异步方法:

 public Task Initialization { get; }

 public MyClass(string language)
 {
        Initialization = InitializeAsync(language);
 }

 private async Task InitializeAsync(string language)
 {
        throw new Exception("Test Exception");
 }

注册一个事件以捕获所有未处理的异常(在OnStartUp方法中):

protected override void OnStartup(StartupEventArgs e)
{
     AppDomain.CurrentDomain.UnhandledException += MyHandler;
            
}

private static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
        MessageBox.Show("Exception", "Caption");
}

问题是UnhandledException事件没有捕获InitializeAsync方法中的异常

这里的question对我来说听起来像是UnhandledException捕获了所有线程中的异常,但对我而言却不是。

我试图删除ConfigureAwait(false),但也无法正常工作。

我使用了UnobservedTaskExceptionDispatcherUnhandledException,但两者都不起作用

当我将异常打包到MyClass构造函数中时,一切正常,但在InitializeAsync方法中却不能

有什么想法吗?

0 个答案:

没有答案