Skip to content

如何停止线程

🏷️ C# 学习 C#

使用 System.Threading.CancellationTokenSource 停止线程。

示例代码

点击查看代码
cs
using System;
using System.Threading;

namespace StopThread
{
    class Program
    {
        static void Main(string args)
        {
            CancellationTokenSource cts = new CancellationTokenSource();
            Thread t = new Thread(() => {
                while (true)
                {
                    if (cts.IsCancellationRequested)
                    {
                        Console.WriteLine("线程被终止!");
                        break;
                    }
                    Console.WriteLine(DateTime.Now.ToString());
                    Thread.Sleep(1000);
                }
            });

            t.Start();
            cts.Token.Register(() => {
                Console.WriteLine("工作线程被终止!");
            });
            Console.ReadLine();

            cts.Cancel();
            Console.ReadLine();
        }
    }
}

输出结果

点击查看输出结果
2016/2/13 20:02:15
2016/2/13 20:02:16
2016/2/13 20:02:17

工作线程被终止!
线程被终止!