【发布时间】:2012-10-18 03:50:45
【问题描述】:
我希望我的 GUI 在阅读 Asynchronous Programming with Async and Await (C# and Visual Basic) 后不会挂起
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;
}
但是,事实并非如此。它仍然挂起。我意识到我需要在DoBusyJob 中添加额外的await
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;
}
【问题讨论】:
-
async 关键字不会神奇地使您的 for 循环代码在后台线程上运行。你想做的是
await Task.Run( () => DoExpensiveCpuCalculations());
标签: c# user-interface responsive-design task-parallel-library async-await