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类型,用于线程间通信。

  • 相关阅读:
    C# 控制反转(IOC: Inverse Of Control) & 依赖注入(DI: Independence Inject)
    英语常见短语汇总001
    ASP.Net Web.config 中引用外部config文件
    CSS样式汇总
    RSA非对称加密算法
    排序算法【2】——快速排序
    cmake引入boost
    boost之algorithm
    tar命令
    欧拉定理
  • 原文地址:https://www.cnblogs.com/feipeng8848/p/11016268.html
Copyright © 2011-2022 走看看