利用Task 里的异步方法更新UI
有时某些程序需要执行时(如取得WebPage的内容),不想要Block住UI,最后完成后再将数据更新到UI上。
这时可以利用Task去执行,最后要更新UI时,再透过Task.ContinueWith将结果呈现出来。
以下我们使用读取WebPage的内容为范例,按下「取得URL内容」的Button后,会起一个Task去做事,所以UI并不会被Block住。如下,
private void btnGetURL_Click(object sender, EventArgs e) { btnGetURL.Enabled = false; string url = txtURL.Text; //让被Call的程序从下一秒开始执行 Task<string> waitT = Task.Factory.StartNew(() => { WebClient client = new WebClient(); client.Encoding = Encoding.UTF8; return client.DownloadString(url); }); waitT.ContinueWith(antecendent => { //将内容传写到TextBox上 txtBody.Text = antecendent.Result; btnGetURL.Enabled = true; }, TaskScheduler.FromCurrentSynchronizationContext()); }
那如果还要加入取消的话,就加入CancellationTokenSource来控制取消,如下,
CancellationTokenSource tokenSource; //取得网页的内容 private void btnGetURL_Click(object sender, EventArgs e) { tokenSource = new CancellationTokenSource(); btnGetURL.Enabled = false; btnCancel.Enabled = true; string url = txtURL.Text; //让被Call的程序从下一秒开始执行 Task<string> waitT = Task.Factory.StartNew(() => { WebClient client = new WebClient(); client.Encoding = Encoding.UTF8; return client.DownloadString(url); }, tokenSource.Token); waitT.ContinueWith(antecendent => { //将内容传写到TextBox上 txtBody.Text = antecendent.Result; btnGetURL.Enabled = true; btnCancel.Enabled = false; }, tokenSource.Token, TaskContinuationOptions.None, TaskScheduler.FromCurrentSynchronizationContext()); } //取消取得网页的内容 private void btnCancel_Click(object sender, EventArgs e) { if (tokenSource != null) { tokenSource.Cancel(); btnGetURL.Enabled = true; btnCancel.Enabled = false; txtBody.Text = "使用者取消!"; } }