using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp3 { class Class3 { CancellationTokenSource source = new CancellationTokenSource(); internal void Run() { CancellationToken token = source.Token; TaskFactory factory = new TaskFactory(token); //创建一个 异步 Task<string> task = factory.StartNew(TestTaskEvent1, token); // task.Start(); Thread.Sleep(15000); //不取消 此函数会一直循环 source.Cancel(); //Console.WriteLine(task.Result); Console.WriteLine("aaaer"); source.Dispose(); } private string TestTaskEvent1(object obj) { while (!source.IsCancellationRequested) { Thread.Sleep(100); } //for (int i = 1; i <= 3; ++i) //{ // Thread.Sleep(1000); //} Console.WriteLine("event over"); return "a"; } internal void Run1() { CancellationTokenSource source = new CancellationTokenSource(); CancellationToken token = source.Token; Task<string> task = new Task<string>(TestTaskEvent, source, token); task.Start(); Thread.Sleep(1500); source.Cancel(); Console.WriteLine(task.Result); //此处会等待Result执行完毕后再执行 Console.WriteLine("aaa"); } string TestTaskEvent(object obj) { for (int i = 1; i <= 3; ++i) { Thread.Sleep(1000); } return "a"; } } }