利用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 = "使用者取消!";
	}
	
}

  

转载于:https://www.cnblogs.com/xfdr0805/articles/6959225.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值