zoukankan      html  css  js  c++  java
  • 使用TaskScheduler 调度器 实现跨线程的控件访问

     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         }
  • 相关阅读:
    spring的常用配置
    aop切入点表达式
    代理模式
    hibernate的常用配置
    正则表达式
    Java配置
    性能提升
    创建vue3 项目
    manjaro
    单调队列
  • 原文地址:https://www.cnblogs.com/yougmi/p/6512647.html
Copyright © 2011-2022 走看看