码迷,mamicode.com
首页 > 其他好文 > 详细

任务取消TASK

时间:2017-08-10 10:23:38      阅读:178      评论:0      收藏:0      [点我收藏+]

标签:oid   cep   generic   .text   throw   cti   ace   factor   new   

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("\nhi,我是OperationCanceledException:{0}\n", 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");
    }
}
}

 

任务取消TASK

标签:oid   cep   generic   .text   throw   cti   ace   factor   new   

原文地址:http://www.cnblogs.com/kexb/p/7337066.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!