c# - 异常未在 Async/Await block 中捕获

标签 c# exception asynchronous task

我刚刚学习在 Windows 窗体应用程序中使用 async/await,试图在执行缓慢操作时保持我的 Windows 应用程序响应。我发现抛出异常的处理有所不同。

如果我使用 WebClient.DownloadStringTaskAsync,我的代码会捕获异常:

private async void button1_Click(object sender, EventArgs e)
{
  try
  {
    this.textBox1.Text = await webClient.DownloadStringTaskAsync("invalid address");
  }
  catch (Exception exc)
  {
    textBox1.Text = exc.Message;
  }
}

但是,如果我在自己的代码中调用异步函数,则不会捕获异常:

private string GetText()
{
  throw new Exception("Tough luck!");
}

private async void button3_Click(object sender, EventArgs e)
{
  using (var webClient = new WebClient())
  {
    try
    {
      this.textBox1.Text = await Task.Run(() => GetText());
    }
    catch (Exception exc)
    {
      textBox1.Text = exc.Message;
    }
  }
}

作为对 stackoverflow 问题 Correct Way to Throw and Catch Exceptions using async/await 的回答有人建议“禁用‘Just My Code’ 工具->选项->调试->常规”

After comments from Daniel Hilgarth (thanks Daniel!), I saw a copy - paste error. I've corrected it here. The problem still remains, but if you follow the advise to disable "just my code", the exception is properly caught.

所以我想问题已经解决了。

最佳答案

问题是这样的:
您正在抛出 Exception 但捕获 WebException

两种解决方案:

  1. 抛出一个WebException
  2. 捕获异常

首选解决方案 1,因为实际上您永远不应该抛出不明确的 Exception

关于c# - 异常未在 Async/Await block 中捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31071316/

相关文章:

javascript - 延迟链接 - 然后在上一个调用因错误完成时调用成功回调

ios - Swift:异步数据任务永远不会终止

javascript - 调用异步函数后代码还执行了多少

c# - 在 WPF 中显示 Drawing.Image

android - 异步任务 "Only the original thread that created a view hierarchy can touch its views."

c# - 提示对话框需要提示选项(参数 'options' )

c# - 为什么 XmlSerializer 抛出 InvalidOperationException?

c# - 如何在 Ajax 调用后更新 session ?

c# - Roslyn 创建自定义表达式

c# - 性能影响 -> 修改 Observable 集合中的对象与删除和添加新对象?