在阅读Async and Await (C# and Visual Basic) 的异步编程之后,我希望我的 GUI 不会挂起
public async Task<string> DoBusyJob()
{
// Busy Job
Thread.Sleep(10000);
i++;
return "Finished " + i;
}
int i = 0;
private async void button1_Click(object sender, EventArgs e)
{
// Hang!
string result = await DoBusyJob();
this.label1.Text = result;
}
但是,事实并非如此。它仍然挂起。我意识到我需要添加额外await
的DoBusyJob
public async Task<string> DoBusyJob()
{
// Busy Job
await Thread.Sleep(10000);
i++;
return "Finished " + i;
}
int i = 0;
private async void button1_Click(object sender, EventArgs e)
{
// OK!
string result = await DoBusyJob();
this.label1.Text = result;
}
我可以知道为什么会这样吗?我真的需要double await
吗?如果出现以下情况怎么办?
public async Task<string> DoBusyJob()
{
// How to prevent Hang?
for (int j = 0; j < 10000000; j++) {
double m = Math.Sqrt(1) + Math.Sqrt(2) + Math.Sqrt(3);
}
i++;
return "Finished " + i;
}
int i = 0;
private async void button1_Click(object sender, EventArgs e)
{
// Hang!
string result = await DoBusyJob();
this.label1.Text = result;
}