TaskScheduler——任务调度器

作者:追风剑情 发布于:2017-11-7 20:47 分类:C#

示例

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TastTest3
{
    public partial class Form1 : Form
    {
        private readonly TaskScheduler m_syncContextTaskScheduler;
        public Form1()
        {
            InitializeComponent();
            //获得对一个同步上下文任务调度器的引用
            m_syncContextTaskScheduler = TaskScheduler.FromCurrentSynchronizationContext();

            label1.Text = "Synchronization Context Task Scheduler Demo";
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private CancellationTokenSource m_cts;

        // 点击窗体任意区域
        protected override void OnMouseClick(MouseEventArgs e)
        {
            if (m_cts != null)//如果操作正在进行,取消它
            {
                m_cts.Cancel();
                m_cts = null;
            }
            else //操作没有开始,启动它
            {
                label1.Text = "Operation running";
                m_cts = new CancellationTokenSource();

                //这个任务使用默认任务调度器,在一个线程池线程上执行
                //线程池上执行的任务不能更新UI组件,否则抛出InvalidOperationException
                Task<Int32> t = Task.Run(()=>Sum(m_cts.Token, 20000), m_cts.Token);

                //下面这些任务使用同步上下文任务调度器,在GUI线程上执行
                t.ContinueWith(task => label1.Text = "Result: " + task.Result, CancellationToken.None, TaskContinuationOptions.OnlyOnRanToCompletion,
                    m_syncContextTaskScheduler);

                t.ContinueWith(task => label1.Text = "Operation canceled", CancellationToken.None, TaskContinuationOptions.OnlyOnCanceled,
                    m_syncContextTaskScheduler);

                t.ContinueWith(task => label1.Text = "Operation faulted", CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted,
                    m_syncContextTaskScheduler);
            }
            base.OnMouseClick(e);
        }

        private static Int32 Sum(CancellationToken ct, Int32 n)
        {
            Int32 sum = 0;
            for (; n > 0; n--)
            {
                //在取消标志引用的CancellationTokenSource上调用Cancel,
                //下面这行代码就会抛出OperationCanceledException
                ct.ThrowIfCancellationRequested();

                //如果n太大,会抛出System.OverflowException
                checked { sum += n; }
            }
            return sum;
        }
    }
}

运行测试

1111.png

2222.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号