15.1 非同步函式簡介
阿新 • • 發佈:2018-12-14
15.1.1 初識非同步型別
1 public partial class AsyncForm : Form 2 { 3 Label label; 4 Button button; 5 public AsyncForm() 6 { 7 InitializeComponent(); 8 label = new Label { Location = new Point(10, 20), Text = "Length" }; 9 button = newButton { Location = new Point(10, 50), Text = "Click" }; 10 button.Click += DisPlayWebSiteLength; 11 AutoSize = true; 12 Controls.Add(label); 13 Controls.Add(button); 14 } 15 async void DisPlayWebSiteLength(object sender, EventArgs e)16 { 17 label.Text = "Fetching"; 18 using (HttpClient client = new HttpClient()) 19 { 20 Task<string> task = client.GetStringAsync("https://www.baidu.com/"); 21 string text = await task; 22 label.Text = text.Length.ToString();23 } 24 } 25 }
15.1.2 分解第一個示例