25.10 前台线程和后台线程
CLR将每个线程要么视为前台线程,要么视为后台线程。一个进程中的所有前台线程停止运行时,CLR强制终止仍在运行的任何后台线程。这些后台线程被直接终止;不会抛出异常。
前台线程应该用于执行确实想完成的任务,应该为非关键的任务使用后台线程。
CLR要提供前台线程和后台线程的概念更好地支持AppDomain。每个AppDomain都可以运行一个单独的应用程序。每个应用程序都有它自己的前台线程。如果一个应用程序退出,造成它的前台线程终止,则CLR仍然需要保持活动并运行,使其他应用程序继续运行。所有应用程序都退出,它们的所有前台线程都终止后,整个进程就可以被销毁了。
C# Codes:
using System;
using System.Threading;
namespace ThreadStudy
{
class Program
{
static void Main(string[] args)
{
Thread thread1 = new Thread(new ThreadStart(Print));
thread1.IsBackground = true;
thread1.Start();
Console.WriteLine("Go on execute main thread~");
Thread.Sleep(10000);
Console.WriteLine("Main thread has executed completely~");
}
static void Print()
{
for (int i = 0; i < 10; i++)
{
Console.WriteLine("Here is running thread1, {0}% of the thread tasks have been completed~",10*i);
Thread.Sleep(2000);
}
}
}
}
执行输出:
Here is running thread1, 0% of the thread tasks have been completed~
Go on execute main thread~
Here is running thread1, 10% of the thread tasks have been completed~
Here is running thread1, 20% of the thread tasks have been completed~
Here is running thread1, 30% of the thread tasks have been completed~
Here is running thread1, 40% of the thread tasks have been completed~
Main thread has executed completely~
Here is running thread1, 50% of the thread tasks have been completed~
Press any key to continue . . .
在一个线程的生存期中,任何时候都可以从前台变成后台,或者从后台变成前台。应用程序的主程序以及通过构造一个Thread对象来显式创建的任何线程都默认为前台线程。另一方面,线程池线程默认为后台线程。此外,由进入托管执行环境的本地(native)代码创建的任何线程都被标记为后台线程。