Che*_*eng 2 c# user-interface task-parallel-library async-await responsive-design
在阅读使用Async和Await的异步编程(C#和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;
}
Run Code Online (Sandbox Code Playgroud)
但事实并非如此.它仍然挂起.我意识到我需要添加额外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;
}
Run Code Online (Sandbox Code Playgroud)
我可以知道为什么会这样吗?我真的需要加倍 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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1287 次 |
| 最近记录: |