class Program11 { private static void ExecuteInForeground() { DateTime start = DateTime.Now; var sw = Stopwatch.StartNew(); Console.WriteLine("Thread {0}: {1}, Priority {2}", Thread.CurrentThread.ManagedThreadId, Thread.CurrentThread.ThreadState, Thread.CurrentThread.Priority); do { Console.WriteLine("Thread {0}: Elapsed {1:N2} seconds", Thread.CurrentThread.ManagedThreadId, sw.ElapsedMilliseconds / 1000.0); Thread.Sleep(500); } while (sw.ElapsedMilliseconds <= 5000); sw.Stop(); } static void Main(string[] args) { //停止所有前台线程后,运行时将停止所有后台线程,并关闭。 var th = new Thread(ExecuteInForeground); //设置为后台线程后,主线程执行完毕后,后台线程将停止,此例子中,不会执行到5s就会停止 //如果是前台线程,将执行到5s才停止 th.IsBackground = true; th.Start(); Thread.Sleep(1000); Console.WriteLine("Main thread ({0}) exiting...", Thread.CurrentThread.ManagedThreadId); // Console.ReadLine(); } }