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

来源:互联网 发布:super java 编辑:程序博客网 时间:2024/06/01 08:26

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

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

 

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

例如 :

 

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

            }

        }

 

        staticvoid Main(string [] args)

        {

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

            Printer p = newPrinter ();

            Thread bgroundThread =

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

            // This is now a background thread.

            bgroundThread.IsBackground = true ;

            bgroundThread.Start();

        }

 

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

例如 :

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

        }

        staticvoid PrintTheNumbers(object state)

        {

            Printer task = (Printer)state;

            task.PrintNumbers();

        }

0 0
原创粉丝点击