异步锁死
异步函数testAsync
private async Task<string> testAsync()
{
await Task.Delay(3000);
return DateTime.Now.ToString();
}
//以下程序调用会锁死,应该是子函数中的Delay和主函数中的this.Text = t.Result;互相锁住了
private void button1_Click(object sender, EventArgs e)
{
Task<string> t = this.testAsync();
this.textBox1.Text = DateTime.Now.ToString();
this.Text = t.Result;
this.textBox2.Text = DateTime.Now.ToString();
}
//以下程序可以正常执行
private async void button3_Click(object sender, EventArgs e)
{
this.Text = await this.testAsync();
this.textBox1.Text = DateTime.Now.ToString();
}
//以下程序可以正常执行,就是说调用异步函数时,主函数必须也要await
private void button2_Click(object sender, EventArgs e)
{
Task t= test2();
}
private async Task test2()
{
Task<string> t = this.testAsync();
this.textBox1.Text = DateTime.Now.ToString();
this.Text = await t;
this.textBox2.Text = DateTime.Now.ToString();
}
参考:
c# async/await异步编程死锁的问题 - F风 - 博客园 (cnblogs.com)
c#Async,await编程核心基础,执行顺序,死锁,使用注意点,_漫游者码农的博客-CSDN博客
总结:
尽量不要用this.Text = t.Result;得到异步结果,要用await t得到结果。
上面死锁的原因是当Task.Delay完成后需切回调用线程执行Task.Delay下面的代码,但原线程却在this.Text = t.Result;处阻塞了,所以就死锁了