编写界面如图:
private async void button1_Click(object sender, EventArgs e){#region 单个执行的异步,效率慢HttpClient wc = new HttpClient();string s1 = await wc.GetStringAsync(textBox1.Text);label1.Text = s1.Length.ToString();string s2 = await wc.GetStringAsync(textBox2.Text);label2.Text = s2.Length.ToString();string s3 = await wc.GetStringAsync(textBox3.Text);label3.Text = s3.Length.ToString();#endregion#region 并发全部完成的异步更快HttpClient hc = new HttpClient();var task1 = hc.GetStringAsync(textBox1.Text);var task2 = hc.GetStringAsync(textBox2.Text);var task3 = hc.GetStringAsync(textBox3.Text);Task.WaitAll(task1, task2, task3);label1.Text = task1.Result.Length.ToString();label2.Text = task2.Result.Length.ToString();label3.Text = task3.Result.Length.ToString();#endregion}
使用异步方法不一定都是 await,只有需要按序执行采用 await。上面的程序改成并发下载, Task.WaitAll 是等待所有任务完成。