1.声明CancellationTokenSource 对象
/// <summary>线程控制器管理</summary> private CancellationTokenSource cancellationManage;
2.实例化 CancellationTokenSource 对象,此对象管理取消通知并将其发送给单个取消标记。并进行注册回调事件
// 初始化线程控制并注册回调函数
cancellationManage = new CancellationTokenSource();
cancellationManage.Token.Register(CallStopThread);
3.Cancel();方法调用会设置cancellationManage.IsCancellationRequested为True;
调用 CancellationTokenSource.Cancel 方法以提供取消通知。 这会将 CancellationToken.IsCancellationRequested 取消标记的每个副本上的属性设置为 true
cancellationManage.Cancel();
测试Demo:
1 class Program 2 { 3 private static CancellationTokenSource cts = null; 4 5 static void Main(string[] args) 6 { 7 while (true) 8 { 9 Console.WriteLine("1.开始运行多线程"); 10 Console.WriteLine("2.取消多线程"); 11 switch (Console.ReadLine()) 12 { 13 case "1": 14 BeginThread(); 15 break; 16 case "2": 17 CancelThread(); 18 break; 19 default: 20 break; 21 } 22 } 23 24 // Console.ReadKey(); 25 } 26 27 /// <summary> 28 /// 回调停止方法 29 /// </summary> 30 private static void CallStopThread() 31 { 32 Console.WriteLine("回调停止方法"); 33 } 34 35 /// <summary> 36 /// 取消方法 37 /// </summary> 38 private static void CancelThread() 39 { 40 cts.Cancel(); 41 } 42 43 /// <summary> 44 /// 开始运行线程方法 45 /// </summary> 46 private static void StartThread() 47 { 48 for (int i = 0; i < 1000000; i++) 49 { 50 if (cts.IsCancellationRequested) break; 51 Console.WriteLine($"开始运行线程方法,线程ID:{Thread.CurrentThread.ManagedThreadId}"); 52 Thread.Sleep(1000); 53 } 54 } 55 56 /// <summary> 57 /// 开始运行线程 58 /// </summary> 59 private static void BeginThread() 60 { 61 Console.WriteLine("开始运行1方法"); 62 cts = new CancellationTokenSource(); 63 cts.Token.Register(CallStopThread); 64 65 Thread[] ths = new Thread[3]; 66 for (int i = 0; i < ths.Count(); i++) 67 { 68 ths[i] = new Thread(StartThread); 69 ths[i].Start(); 70 } 71 72 } 73 }
CancellationTokenSource 取消多线程操作
原文:https://www.cnblogs.com/yunchen/p/15034271.html