首页 > 代码库 > 任务取消TASK
任务取消TASK
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"); } } }
任务取消TASK
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。