在Task中用CancellationTokenSource来取消任务,可以手动 cancelTokenSource.Cancel()取消,还有new时就设置取消时间var cancelTokenSource = new CancellationTokenSource(2000); 也可以在任务中 cancelTokenSource.CancelAfter(2000)实现同样的效果。
var cancelTokenSource = new CancellationTokenSource(); //var cancelTokenSource = new CancellationTokenSource(2000); Task.Run(() => { //cancelTokenSource.CancelAfter(2000); while (!cancelTokenSource.IsCancellationRequested) { Console.WriteLine(DateTime.Now); Thread.Sleep(1000); } }, cancelTokenSource.Token); Console.WriteLine("Press any key to cancel"); Console.ReadLine(); cancelTokenSource.Cancel(); Console.WriteLine("Done");