我刚刚学习在 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
。
两种解决方案:
- 抛出一个
WebException
- 捕获
异常
首选解决方案 1,因为实际上您永远不应该抛出不明确的 Exception
。
关于c# - 异常未在 Async/Await block 中捕获,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31071316/