【问题标题】:how to check async task is null or not如何检查异步任务是否为空
【发布时间】:2020-01-15 07:58:51
【问题描述】:

我使用 WebClient 和异步方法调用 API,现在我想管理可能的错误,例如为 null 我使用了 try/catch,但没有一个异常起作用并且无法捕获错误

如何发现错误?

private async Task<string> GetTaskAsync(string API)
{
    try
    {
        using (WebClient client = new WebClient())
        {
            client.Encoding = Encoding.UTF8;
            return await client.DownloadStringTaskAsync(API);
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        return null;
    }
    catch (NullRefrenceException ex)
    {
        Console.WriteLine(ex.Message);
    }
}

【问题讨论】:

  • 你的意思是任务为空还是任务的结果为空?任务永远不应该为空。
  • @PauloMorgado 我的意思是任务结果
  • 它与任何其他值没有什么不同。

标签: c# asynchronous async-await try-catch webclient


【解决方案1】:

您应该更改捕获的顺序。 NullReferenceException 派生自 Exception 类,因此如果发生 NullReferenceException,它将被第一个 catch 块捕获。您应该执行以下操作。

try
{
  using (WebClient client = new WebClient())
  {
    client.Encoding = Encoding.UTF8;
    return await client.DownloadStringTaskAsync(API);
  }
}
catch (NullRefrenceException ex)
{
   Console.WriteLine(ex.Message);
}
catch (Exception ex)
{
  Console.WriteLine(ex.Message);
  return null;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 1970-01-01
    • 2022-12-18
    • 1970-01-01
    • 2020-01-27
    相关资源
    最近更新 更多