首页 > 代码库 > 多任务同时取消

多任务同时取消

 1  class Program
 2     {
 3         static System.Threading.CancellationTokenSource cancelTokenSource = new System.Threading.CancellationTokenSource();
 4         static void Main(string[] args)
 5         {
 6             Task.Factory.StartNew(MyTask_1, cancelTokenSource.Token);
 7             Task.Factory.StartNew(MyTask_2, cancelTokenSource.Token);
 8 
 9             Console.WriteLine("请按Enter键停止");
10             Console.ReadLine();
11             cancelTokenSource.Cancel();
12             Console.WriteLine("已停止");
13             Console.ReadLine();
14 
15         }
16         static void MyTask_1()
17         {
18             //判断是否任务取消
19             while (!cancelTokenSource.IsCancellationRequested)
20             {
21                 Console.WriteLine($"MyTask_1:{DateTime.Now}");
22                 System.Threading.Thread.Sleep(1000);
23             }
24         }
25 
26         static void MyTask_2()
27         {
28             //判断是否任务取消
29             while (!cancelTokenSource.IsCancellationRequested)
30             {
31                 Console.WriteLine($"MyTask_2:{DateTime.Now}");
32                 System.Threading.Thread.Sleep(1000);
33             }
34         }
35 }

参考文献:http://www.cnblogs.com/wlzhang/p/4604471.html

多任务同时取消