Nic*_*rus 3 c# concurrency async-await
这是我在Windows Forms Application中实现的async/await
async Task<int> DoAysnc1()
{
await Task.Delay(3000);
return 3000;
}
async Task<int> DoAsync2()
{
await Task.Delay(5000);
return 5000;
}
private async void button1_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
var doAsync1 = DoAysnc1();
var doAsync2 = DoAysnc2();
var async1 = await doAsync1;
var async2 = await doAsync2;
this.textBox1.Text = $"{async1} & {async2}";
}
Run Code Online (Sandbox Code Playgroud)
5秒后,TextBox中的结果为" 3000 & 5000".
但是,当我button1_Click像这样修改:
private async void button1_Click(object sender, EventArgs e)
{
this.textBox1.Text = "";
var async1 = await DoAysnc1();
var async2 = await DoAysnc2();
this.textBox1.Text = $"{async1} & {async2}";
}
Run Code Online (Sandbox Code Playgroud)
结果相同,但需要8秒.
为什么第二版的button1_Click行为同步?
以下是对差异的解释:
this.textBox1.Text = "";
var doAsync1 = DoAysnc1(); // <--- Run DoAsync1
var doAsync2 = DoAysnc2(); // <--- Run DoAsync2
var async1 = await doAsync1; // <--- wait for DoAsync1 to finish
var async2 = await doAsync2; //<--- wait for DoAsync2 to finish
this.textBox1.Text = $"{async1} & {async2}";
Run Code Online (Sandbox Code Playgroud)
而:
this.textBox1.Text = "";
var async1 = await DoAysnc1(); // <-- Run DoAsync1 and wait for it to be done
var async2 = await DoAysnc2(); // <-- Run DoAsync2 and wait for it to be done
this.textBox1.Text = $"{async1} & {async2}";
Run Code Online (Sandbox Code Playgroud)
因此在第一个版本中,两个任务都在同一时间运行.在第二个版本中,您从未运行第二个任务,直到第一个任务完成.
我认为阅读这篇文章对你的知识来说将是一个很大的好处.