1. 程式人生 > >C# 執行緒池中取消執行緒的三種方式

C# 執行緒池中取消執行緒的三種方式

三種方式都使用CancellationToken,只是使用方式不同,有類似於採用全域性標誌位的方式

第一種 檢測IsCancellationRequested方式

        static void AsyncOperation1(CancellationToken token)
        {
            Console.WriteLine("starting the first task");
            for (int i = 0; i < 5; i++)
            {
                //取消任務訊號
                if (token.IsCancellationRequested)
                {
                    Console.WriteLine("the first task has been canceled.");
                    return;
                }

                Thread.Sleep(TimeSpan.FromSeconds(1));
            }
            Console.WriteLine("the first task has completed successfully");
        }


第二種 丟擲ThrowIfCancellationRequested方式

        static void AsyncOperation2(CancellationToken token)
        {
            try
            {
                Console.WriteLine("starting the second task");
                for (int i = 0; i < 5; i++)
                {
                    //取消任務訊號
                    token.ThrowIfCancellationRequested();
                    Thread.Sleep(TimeSpan.FromSeconds(1));
                }
                Console.WriteLine("the second task has completed successfully");
            }
            catch(OperationCanceledException)
            {
                Console.WriteLine("the second task has been canceled.");
            }
        }


第三種 註冊取消方法方式

        static void AsyncOperation3(CancellationToken token)
        {
            bool cancellationFlag = false;
            //取消任務訊號,改變標誌位
            token.Register(() => cancellationFlag = true);
            Console.WriteLine("starting the third task");
            for(int i = 0; i < 5; i ++)
            {
                if(cancellationFlag)
                {
                    Console.WriteLine("the third task has been canceled.");
                    return;
                }
                Thread.Sleep(TimeSpan.FromSeconds(1));
            }

            Console.WriteLine("the third task has completed successfully");
        }


測試方式

        static void Main(string[] args)
        {
            using (var cts = new CancellationTokenSource())
            {
                CancellationToken token = cts.Token;
                ThreadPool.QueueUserWorkItem(_ => AsyncOperation1(token));
                Thread.Sleep(TimeSpan.FromSeconds(3));
                cts.Cancel();
            }
            //Thread.Sleep(TimeSpan.FromSeconds(3));
            using (var cts = new CancellationTokenSource())
            {
                CancellationToken token = cts.Token;
                ThreadPool.QueueUserWorkItem(_ => AsyncOperation2(token));
                Thread.Sleep(TimeSpan.FromSeconds(3));
                cts.Cancel();
            }
            //Thread.Sleep(TimeSpan.FromSeconds(3));
            using (var cts = new CancellationTokenSource())
            {
                CancellationToken token = cts.Token;
                ThreadPool.QueueUserWorkItem(_ => AsyncOperation3(token));
                Thread.Sleep(TimeSpan.FromSeconds(3));
                cts.Cancel();
            }

            Console.ReadKey();
        }