CancellationTokenSource
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); } }
人各有命,上天注定,有人天生为王,有人落草为寇。脚下的路,如果不是你自己的选择,那么旅程的终点在哪,也没人知道。你会走到哪,会遇到谁,都不一定。