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

  • 相关阅读:
    使页面左右无法滑动(手机端)
    git使用简易指南(转)
    sql2012笔记
    C#的应用
    细谈HTML解析模块
    poj2299解题报告(归并排序求逆序数)
    poj2388解题报告(排序)
    poj3080解题报告(暴力、最大公共子串)
    poj1068解题报告(模拟类)
    poj3295解题报告(构造、算术表达式运算)
  • 原文地址:https://www.cnblogs.com/feipeng8848/p/11016268.html
Copyright © 2011-2022 走看看