码迷,mamicode.com
首页 > 编程语言 > 详细

使用TaskScheduler 调度器 实现跨线程的控件访问

时间:2017-03-07 08:36:35      阅读:204      评论:0      收藏:0      [点我收藏+]

标签:sum   bsp   sync   nbsp   res   ant   启动   string   访问   

技术分享

 1         //任务调度器
 2         TaskScheduler UIscheduler = null;
 3         public Form1()
 4         {
 5             //获取任务调度器
 6             UIscheduler = TaskScheduler.FromCurrentSynchronizationContext();
 7             InitializeComponent();
 8         }
 9 
10         private void btnTaskScheduler_Click(object sender, EventArgs e)
11         {
12             System.Threading.CancellationTokenSource cts = new System.Threading.CancellationTokenSource();
13             //启动一个任务线程
14             Task<int> t = Task.Run(() =>Sum(100));
15             //使用UIscheduler 调度器 实现跨线程的控件访问
16             t.ContinueWith(task => txtRes.Text = t.Result.ToString(), cts.Token,TaskContinuationOptions.OnlyOnRanToCompletion,UIscheduler);
17             t.ContinueWith(task => txtRes.Text = "Error",System.Threading.CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted,UIscheduler);
18         }
19         private int Sum(int num)
20         {
21             int res = 0;
22             for (int i = 0; i <= num; i++)
23             {
24                 checked { res += i; }
25                 //res += i;
26             }
27             return res;
28         }

 

使用TaskScheduler 调度器 实现跨线程的控件访问

标签:sum   bsp   sync   nbsp   res   ant   启动   string   访问   

原文地址:http://www.cnblogs.com/yougmi/p/6512647.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!