C# Thread IsBackground 前后台線程


Thread 區別前后台線程屬性IsBackground

1、  創建一個線程默認是前台線程,即IsBackground=true

2、  主線程的結束會關聯前台線程,前台線程會阻止主進程的結束,需等待前台線程完成。

3、  主進程結束時后台線程也會結束,即使沒有執行完成也會被中斷。

        static void Main(string[] args)
        {
            BackgroundTest shortTest = new BackgroundTest(50);
            Thread foregroundThread =
                new Thread(new ThreadStart(shortTest.RunLoop));
            foregroundThread.Name = "ForegroundThread";

            BackgroundTest longTest = new BackgroundTest(100);
            Thread backgroundThread =
                new Thread(new ThreadStart(longTest.RunLoop));
            backgroundThread.Name = "BackgroundThread";
            backgroundThread.IsBackground = true;

            foregroundThread.Start();
            backgroundThread.Start();
           Task.Factory.StartNew(() =>
            {
                Thread.CurrentThread.Name = "Task Thread";
                Thread.CurrentThread.IsBackground = false; //設置為前台線程
                new BackgroundTest(50).RunLoop();
            });
//回車結束主線程,如果有前台線程在運行是無法結束的,(后台線程就會被終止,不會執行完成)
            Console.ReadLine();
        }

        class BackgroundTest
        {
            int maxIterations;

            public BackgroundTest(int maxIterations)
            {
                this.maxIterations = maxIterations;
            }

            public void RunLoop()
            {
                String threadName = Thread.CurrentThread.Name;

                for (int i = 0; i < maxIterations; i++)
                {
                    Console.WriteLine("{0} count: {1}",
                        threadName, i.ToString());
                    Thread.Sleep(250);
                }
                Console.WriteLine("{0} finished counting.", threadName);
            }
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM