using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ConsoleApp72 { internal class Program { static Thread t1 { get; set; } static System.Timers.Timer tmr { get; set; } static void Main(string[] args) { try { tmr = new System.Timers.Timer(); tmr.Elapsed += Tmr_Elapsed; tmr.Interval = 5000; tmr.Start(); t1 = new Thread(() => { PrintNum(10); }); t1.Start(); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.WriteLine("Hello, World!"); Console.ReadLine(); } private static void Tmr_Elapsed(object sender, System.Timers.ElapsedEventArgs e) { try { if(t1.IsAlive) { Console.WriteLine("t1 aborted!"); t1.Abort(); tmr.Stop(); Console.WriteLine("Timer stopped!"); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } static void PrintNum(int num) { for (int i = 0; i < num; i++) { Console.WriteLine(i); Thread.Sleep(1000); } } } }
标签:tmr,Console,thread,timespan,C#,System,t1,WriteLine,using From: https://www.cnblogs.com/Fred1987/p/18406950