public static void work(CancellationToken cancellation) { Thread.Sleep(10000); //while (true) //{ Console.WriteLine("结束" + DateTime.Now.ToString("yyyyMMddHHmmss")); if (cancellation.IsCancellationRequested) { throw new OperationCanceledException("结束"); } //} } static void Main(string[] args) { { Console.WriteLine("开始" + DateTime.Now.ToString("yyyyMMddHHmmss")); var cancelSource = new CancellationTokenSource(); cancelSource.CancelAfter(30000); var t = new Thread(() => { try { work(cancelSource.Token); } catch (OperationCanceledException e) { Console.WriteLine(e.Message); throw; } }); t.Start(); t.Join(); Console.WriteLine(t.ThreadState); Console.WriteLine(t.IsAlive); } }
标签:cancelSource,Console,DateTime,CancellationTokenSource,WriteLine,new From: https://www.cnblogs.com/ZkbFighting/p/16887782.html