【问题标题】:Throw new Exception in asyc method在异步方法中抛出新异常
【发布时间】:2018-07-02 15:27:59
【问题描述】:

如何在异步方法中正确抛出异常?

public async void Method()
{
  if(value)
    throw new Exception("Error!");
}

【问题讨论】:

    标签: c# asynchronous exception methods throw


    【解决方案1】:

    类似,但返回Task。当你awaitTask时,它会在调用者中抛出异常。

    public async Task DoSomethingAsync()
    {
        throw new Exception("Error!");
    }
    
    await DoSomethingAsync(); // throws
    

    您几乎不想使用async void,因为您将无法等待它完成、获取返回值或抛出任何异常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-10
      • 2014-05-15
      • 1970-01-01
      • 2018-04-09
      • 2020-01-28
      • 1970-01-01
      • 1970-01-01
      • 2013-01-01
      相关资源
      最近更新 更多