【发布时间】:2012-06-05 10:17:00
【问题描述】:
从我在代码中遇到的问题开始,我创建了这个简单的应用程序来重现问题:
private async void button1_Click(object sender, EventArgs e)
{
Task task = Task.Run(() =>
{
TestWork();
});
try
{
await task;
MessageBox.Show("Exception uncaught!");
}
catch (Exception) { MessageBox.Show("Exception caught!"); }
}
private async void button2_Click(object sender, EventArgs e)
{
Task task = TestWork();
try
{
await task;
MessageBox.Show("Exception uncaught!");
}
catch (Exception) { MessageBox.Show("Exception caught!"); }
}
private async Task TestWork()
{
throw new Exception();
}
button1_Click 的代码不会捕获异常。我已经验证这是因为我没有等待 TestWork async 方法。事实上,我收到了来自 Visual Studio 的警告消息,通知我我没有等待该方法。但是,解决方案可以编译,如果我广泛使用 async/await,我担心这会发生在我的代码中的其他地方。那么您能否解释一下原因,并给出一些避免它的黄金法则?
P.S.:如果在 button1_Click 我写的代码中,它可以工作:
Task task = Task.Run(async () =>
{
await TestWork();
});
【问题讨论】:
-
另一种正确编写
button1_Click代码的方法是Task.Run(() => TestWork())。
标签: c# exception async-await uncaught-exception