任务取消TASK

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApplication15
{
    class Program
    {
        static void Main(string[] args)
        {

            var cts = new CancellationTokenSource();
            var ct = cts.Token;


            Task task1 = new Task(() => { Run1(ct); }, ct);

            Task task2 = new Task(Run2);


            task1.Start();
            task2.Start();

            Task.Factory.StartNew(() =>
            {
                Thread.Sleep(15 * 1000);
                cts.Cancel();
                try
                {

                    task1.Wait();
                    task2.Wait();
                }
                catch (AggregateException ex)
                {
                    foreach (var e in ex.InnerExceptions)
                    {
                        Console.WriteLine("
hi,我是OperationCanceledException:{0}
", e.Message);
                    }


                    Console.WriteLine("task1是不是被取消了? {0}", task1.IsCanceled);
                    Console.WriteLine("task2是不是被取消了? {0}", task2.IsCanceled);
                }

            });


      


        Console.ReadLine();


        }
    static void Run1(CancellationToken ct)
    {


        Console.WriteLine("我是任务1");

        while (true)
        {
            ct.ThrowIfCancellationRequested();
            Thread.Sleep(1000);
            ct.ThrowIfCancellationRequested();
            Thread.Sleep(1000);
            ct.ThrowIfCancellationRequested();
            Thread.Sleep(1000);
            ct.ThrowIfCancellationRequested();
            Thread.Sleep(1000);
            ct.ThrowIfCancellationRequested();
            Thread.Sleep(2000);

        }
        ct.ThrowIfCancellationRequested();
        Console.WriteLine("我是任务1的第二部分信息");
    }

    static void Run2()
    {
     
        Console.WriteLine("我是任务2");
    }
}
}
原文地址:https://www.cnblogs.com/kexb/p/7337066.html