异步函数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();
}