我正在关注 MSDN 上的await教程,并试图找出 using await
as a statement与 using await
as an expression之间的区别。这整个 async-await 事情让我心烦意乱,我找不到这个特殊情况的任何例子。
基本上,我想看看如何await
异步使用多个 s,这意味着我不想在第二个开始之前等待第一个完成。对我来说,这违背了异步的目的:
private async void button1_Click(object sender, EventArgs e)
{
// Using await as an expression
string result_a = await WaitAsynchronouslyAsync();
string result_b = await WaitAsynchronouslyAsync();
// This takes six seconds to appear
textBox1.Text = result_a + Environment.NewLine;
textBox1.Text += result_b;
}
public async Task<string> WaitAsynchronouslyAsync()
{
await Task.Delay(3000);
return "Finished";
}
然而,通过一个细微的改变,两个“Finished”的出现总共只需要 3 秒,这就是我想要的——这两个await
s 真正异步运行:
private async void button1_Click(object sender, EventArgs e)
{
var a = WaitAsynchronouslyAsync();
var b = WaitAsynchronouslyAsync();
// Using await as a statement
await a;
await b;
// This takes three seconds to appear
textBox1.Text = a.Result + Environment.NewLine;
textBox1.Text += b.Result;
}
我的问题是,为什么这些行为不同?我在这里错过了什么微妙的点?