using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApplication15 { class Program { static void Main(string[] args) { var cts = new CancellationTokenSource(); var ct = cts.Token; Task task1 = new Task(() => { Run1(ct); }, ct); Task task2 = new Task(Run2); task1.Start(); task2.Start(); Task.Factory.StartNew(() => { Thread.Sleep(15 * 1000); cts.Cancel(); try { task1.Wait(); task2.Wait(); } catch (AggregateException ex) { foreach (var e in ex.InnerExceptions) { Console.WriteLine("\nhi,我是OperationCanceledException:{0}\n", e.Message); } Console.WriteLine("task1是不是被取消了? {0}", task1.IsCanceled); Console.WriteLine("task2是不是被取消了? {0}", task2.IsCanceled); } }); Console.ReadLine(); } static void Run1(CancellationToken ct) { Console.WriteLine("我是任务1"); while (true) { ct.ThrowIfCancellationRequested(); Thread.Sleep(1000); ct.ThrowIfCancellationRequested(); Thread.Sleep(1000); ct.ThrowIfCancellationRequested(); Thread.Sleep(1000); ct.ThrowIfCancellationRequested(); Thread.Sleep(1000); ct.ThrowIfCancellationRequested(); Thread.Sleep(2000); } ct.ThrowIfCancellationRequested(); Console.WriteLine("我是任务1的第二部分信息"); } static void Run2() { Console.WriteLine("我是任务2"); } } }
时间: 2024-12-17 17:57:29