前台线程(Foreground Threads)和后台线程(Background Threads)

不要将前台线程 (Foreground Threads) 和后台线程 (Background Threads)

指和常说的主线程 ( Primary Thread)和工作者线程 (Worker Thread) 混淆。

它们的定义如下 :

 

前台线程 (Foreground Threads):  前台线程可以阻止程序退出。除非所有前台线程都结束,否则 CLR不会关闭程序。

后台线程 (Background Threads) 有时候也叫 Daemon Thread 。他被 CLR 认为是不重要的执行路径,可以在任何时候舍弃。因此当所有的前台线程结束,即使还有后台线程在执行, CLR 也会关闭程序。

 

使用 Thread 类启动一个线程默认就是前台线程 (Foreground Threads) ,但是可以通过给 IsBackground 赋值将线程转变为后台线程。

例如 :

 

        public class Printer

        {

            public void PrintNumbers()

            {

                // Display Thread info.

                Console .WriteLine("-> {0} is executing PrintNumbers()" ,

                Thread .CurrentThread.Name);

                // Print out numbers.

                Console .Write("Your numbers: " );

                 for (int i = 0; i < 10; i++)

                {

                    Console .Write("{0}, " , i);

                    Thread .Sleep(2000);

                }

                Console .WriteLine();

            }

        }

 

        static void Main(string [] args)

        {

            Console .WriteLine("***** Background Threads *****\n" );

            Printer p = new Printer ();

            Thread bgroundThread =

                  new Thread (new ThreadStart (p.PrintNumbers));

            // This is now a background thread.

            bgroundThread.IsBackground = true ;

            bgroundThread.Start();

        }

 

另外从 ThreadPool 里面去的的线程默认是后台线程 (Background Threads)

例如 :

        static void Main(string [] args)

        {

            Console .WriteLine("***** Fun with the CLR Thread Pool *****\n" );

            Console .WriteLine("Main thread started. ThreadID = {0}" ,

            Thread .CurrentThread.ManagedThreadId);

            Printer p = new Printer();

            WaitCallback workItem = new WaitCallback (PrintTheNumbers);

            // Queue the method ten times.

            for (int i = 0; i < 10; i++)

            {

                ThreadPool .QueueUserWorkItem(workItem, p);

            }

            Console .WriteLine("All tasks queued" );

 

            Console .ReadLine();

        }

        static void PrintTheNumbers(object state)

        {

            Printer task = (Printer)state;

            task.PrintNumbers();

        }

 

原文地址:https://www.cnblogs.com/findcaiyzh/p/1979548.html