多线程(四):前台和后台线程

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();
        }
    }

 

posted @ 2018-10-28 13:51  幸福安康  阅读(224)  评论(0编辑  收藏  举报