正確中止線程

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();
        }
    }
}
相關文章
相關標籤/搜索