为什么不能通过catch捕获异步void方法的异常?

时间:2018-10-19 22:06:35

标签: c# asynchronous task void

因此,我开始阅读有关异步方法的内容,并且遇到了许多我认为理所当然的语句,例如:

“异步虚假方法的异常无法捕获。”

这是为什么,有人可以解释一下吗?从下面的示例中,这对我来说并不明显,谢谢。

private async void ThrowExceptionAsync()
{
  throw new InvalidOperationException();
}
public void AsyncVoidExceptions_CannotBeCaughtByCatch()
{
  try
  {
    ThrowExceptionAsync();
  }
  catch (Exception)
  {
    // The exception is never caught here!
    throw;
  }
}

如果我这样重写它会怎样:

public void AsyncVoidExceptions_CannotBeCaughtByCatch()
    {
      try
      {
        throw new InvalidOperationException();
      }
      catch (Exception)
      {
        // IS THE EXCEPTION STILL NEVER CAUGHT HERE? what's the difference?
        throw;
      }
    }

0 个答案:

没有答案