Async exception not being caught or being swallowed

前端 未结 3 1123
自闭症患者
自闭症患者 2021-01-23 09:26

Update from the future: TL;DR to catch expressions in async methods you have to await, Task.WaitAll, or .Result.

相关标签:
3条回答
  • 2021-01-23 09:53

    You can handle unobserved Task exceptions as follows:

    TaskScheduler.UnobservedTaskException += (object sender, UnobservedTaskExceptionEventArgs eventArgs) =>
    {
          eventArgs.SetObserved();
          ((AggregateException)eventArgs.Exception).Handle(ex =>
          {
              //TODO: inspect type and handle exception
              return true;
          });
    };
    
    0 讨论(0)
  • 2021-01-23 10:04

    When an async method throws an exception, that exception is placed on the returned Task. It's not raised directly to the caller. This is by design.

    So, you have to either await the Task returned from LoadMSpecAsync or have your mSpecCompletionHandler examine its Task argument for exceptions. It will show up there.

    0 讨论(0)
  • 2021-01-23 10:09

    I'm going to add an answer to my own question because there's a useful piece of information that I found out. The intermediary method LoadMSpecAsync is swalloing the exception. For this not to happen it needs a little teak. You need to add the async keyword before the return type and the "await" keyword after "return".

    0 讨论(0)
提交回复
热议问题