1. 程式人生 > 其它 >CancellationTokenSource 取消多執行緒操作

CancellationTokenSource 取消多執行緒操作

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 }