.Net中后台线程和前台线程的区别

.Net中的线程,可以分为后台线程和前台线程。后台线程与前台线程并没有本质的区别,它们之间唯一的区别就是:应用程序必须运行完所有的前台线程才可以退出;而对于后台线程,应用程序则可以不考虑其是否已经运行完毕而直接退出,所有的后台线程在应用程序退出时都会自动结束。其实,说白了就是当前台线程都结束了的时候,整个程序也就结束了,即使还有后台线程正在运行,此时,所有剩余的后台线程都会被停止且不会完成.但是,只要还有一个前台线程没有结束,那么它将阻止程序结束.这就是为什么有些设计不够完美的WinForm程序,在某种特定的情况下,即使所有的窗口都关闭了,但是在任务管理器的管理列表里仍然可以找到该程序的进程,仍然在消耗着CPU和内存资源.因此,在WinForm程序中,关闭所有窗口前,应该停止所有前台线程,千万不要遗忘了某个前台线程.应用程序进程的存亡由前台线程决定而于后台线程无关.这就是它们的区别.线程默认为前台线程。
此外,改变线程从前台到后台不会以任何方式改变它在CPU协调程序中的优先级和状态。因为前台后线程与程序进程的优先级无关.
下面的代码示例对比了前台线程与后台线程的行为。创建一个前台线程和一个后台线程。前台线程使进程保持运行,直到它完成它的 while 循环。前台线程完成后,进程在后台线程完成它的 while 循环之前终止。
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;

namespace TestBackgroundThread
{
    class Program
    {
        static void Main()
        {
            BackgroundTest shortTest = new BackgroundTest(10);
            Thread foregroundThread =
                new Thread(new ThreadStart(shortTest.RunLoop));
            foregroundThread.Name = "前台线程";

            BackgroundTest longTest = new BackgroundTest(50);
            Thread backgroundThread =
                new Thread(new ThreadStart(longTest.RunLoop));
            backgroundThread.Name = "后台线程";
            backgroundThread.IsBackground = true;

            foregroundThread.Start();
            backgroundThread.Start();

            //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(500);
            }
            Console.WriteLine("{0} finished counting.", threadName);
        }
    }
}

原文地址:https://www.cnblogs.com/junior/p/2364193.html