===========================Parallel.For()方法的取消

(在1秒钟之后取消并行循环)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            //通知 CancellationToken,告知其应被取消
            CancellationTokenSource cts = new CancellationTokenSource();
            //注册一个委托,在取消时触发
            cts.Token.Register(() => Console.WriteLine("取消构架触发"));
            //新建一个任务,用于在1秒钟之后取消并行循环
            Task t = new Task(() => {
                Thread.Sleep(1000);
                //传达取消请求
                cts.Cancel();
            });
            //启动任务
            t.Start();
 
            try
            {
                //并行循环
                Parallel.For(0, 10, new ParallelOptions() { CancellationToken = cts.Token }, i =>
                {
                    Console.WriteLine(i);
                });
            }
            //调用的块没有完成就取消架构,则会抛出OperationCanceledException异常
            catch (OperationCanceledException e)
            {
                Console.WriteLine("抛出OperationCanceledException异常");
            }
 
            Console.ReadKey();
        }
    }
}

 

===========================任务的取消

(在1秒钟之后取消任务)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            //通知 CancellationToken,告知其应被取消
            CancellationTokenSource cts = new CancellationTokenSource();
            //注册一个委托,在取消时触发
            cts.Token.Register(() => { Console.WriteLine("取消构架触发"); });
            //新建一个任务,用于在1秒钟之后取消任务
            Task t = new Task(() => {
                Thread.Sleep(1000);
                cts.Cancel();
            });
            t.Start();

            //任务
            TaskFactory sf = new TaskFactory(cts.Token);
            Task tsf= sf.StartNew(() => {
                for (int i = 0; i < 10; i++)
                {
                    Console.WriteLine(i);
                }
            });
            try
            {
                //等待任务执行完成
                tsf.Wait();
            }
            //调用的块没有完成就取消架构,则会抛出AggregateException异常
            catch (AggregateException)
            {
                Console.WriteLine("抛出AggregateException异常");
            }
           
            Console.ReadKey();

        }
    }
}