正确停止线程

using System;
using System.Threading;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var p = new Program();
            p.Do();
            p.Stop();
        }

        CancellationTokenSource cts = new CancellationTokenSource();

        void Do()
        {
            var worker = new Thread(() =>
            {
                while (true)
                {
                    if (cts.Token.IsCancellationRequested) //检查是否有取消请求
                    {
                        //处理收尾工作
                        Console.WriteLine("this worker was stoped");
                        break;
                    }

                    Console.WriteLine(DateTime.Now);
                    Thread.Sleep(1000);
                }
            });
            worker.Start();
        }

        void Stop()
        {
            Console.ReadKey();
            cts.Cancel(); //发出取消请求
            cts.Token.Register(() => { //进程被停止后通知
                Console.WriteLine("worker has been stoped!");
            });
            Console.ReadKey();
        }
    }
}

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。