zoukankan      html  css  js  c++  java
  • 可取消可报告进度的Task

    using System;
    using System.Threading;
    using System.Threading.Tasks;
    using System.Windows;
    
    namespace WpfApp2
    {
        public partial class MainWindow : Window
        {
            CancellationTokenSource Cts = new CancellationTokenSource();
            public MainWindow()
            {
                Person p = new Person();
                p.Do(Cts.Token, new Progress<int>((xpp)=>label.Content=xpp));
            }
    
            /// <summary>
            /// 按钮按下事件处理函数
            /// </summary>
            /// <param name="sender"></param>
            /// <param name="e"></param>
            private void Button_Click(object sender, RoutedEventArgs e)
            {
                Cts.Cancel();
            }
        }
    
    
        public class Person
        {
            public string name { get; set; }
            public string age { get; set; }
            public int length { get; set; }
            public void Do(CancellationToken token, IProgress<int> progress)
            {
                Action action = new Action(() =>
                {
                    try
                    {
                        for (int i = 0; i < 30; i++)
                        {
                            Thread.Sleep(1000);
                            //报告进度
                            progress.Report(i);
                            //如果用户执行CancellationTokenSource.Cancel()方法就抛出异常
                            //从而达到取消线程操作
                            token.ThrowIfCancellationRequested();
                        }
                    }
                    catch (Exception)
                    {
                        Console.WriteLine("取消线程执行");
                    }
                });
    
                Task task = new Task(action,token);
                task.Start();
            }
        }
    }
    
    


    这里有一点需要说明,那就是Progress实际上是跨线程修改控件,去system.Progress源码中找到Report的源码中调用了OnReport函数,如下图:
    m_synchronizationContext变量是个SynchronizationContext类型,用于线程间通信。

  • 相关阅读:
    机器学习之逻辑回归
    机器学习之线性回归与模型保存
    机器学习之决策树
    机器学习之贝叶斯算法
    机器学习之KNN算法
    算法基础与开发流程
    特征选择与特征降维
    特征预处理
    RSA加密算法和签名算法
    Java中使用OpenSSL生成的RSA公私钥
  • 原文地址:https://www.cnblogs.com/feipeng8848/p/11016268.html
Copyright © 2011-2022 走看看