using System;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        //声明CancellationTokenSource对象
        static CancellationTokenSource cancelTokenSource = new CancellationTokenSource();

        //程序入口
        static void Main(string[] args)
        {
            Task.Factory.StartNew(MyTask, cancelTokenSource.Token);

            Console.WriteLine("请按回车键(Enter)停止");
            Console.ReadLine();

            cancelTokenSource.Cancel();

            Console.WriteLine("已停止");
            Console.ReadLine();
        }

        //测试方法
        static void MyTask()
        {
            //判断是否取消任务
            while (!cancelTokenSource.IsCancellationRequested)
            {
                Console.WriteLine(DateTime.Now);
                Thread.Sleep(1000);
            }
        }
    }
}

 

posted on 2018-12-25 09:44  chester·chen  阅读(1028)  评论(0编辑  收藏  举报