参考自:http://msdn.microsoft.com/zh-cn/library/system.threading.thread.isbackground.aspx
一个线程或者是后台线程或者是前台线程(二选一),在C#中,可以通过属性Thread.IsBackground来获取或设置。
默认新创建的线程为前台线程!
public bool IsBackground { get; set; }
命名空间:using System.Threading;
后台线程与前台线程类似,
区别是:后台线程不会阻止进程的终止,即,当进程中的所有前台线程都执行结束之后,公共语言运行时(CLR)就会结束该进程,而不管后台线程的结束与否。
代码示例:
下面的代码示例对比了前台线程与后台线程的行为。 创建一个前台线程和一个后台线程。 前台线程使进程保持运行,直到它完成它的 while 循环。 前台线程完成后,进程在后台线程完成它的 while 循环之前终止。
主函数:
static void Main(string[] args)
{
//前台线程的回调
BackgroundTest shortTest = new BackgroundTest(10);
//创建前台线程
Thread foregroundThread = new Thread(new ThreadStart(shortTest.RunLoop));
foregroundThread.Name = "ForegroundThread";
//后台线程的回调
BackgroundTest longTest = new BackgroundTest(50);
//创建后台线程
Thread backgroundThread = new Thread(new ThreadStart(longTest.RunLoop));
backgroundThread.Name = "BackgroundThread";
//设置为后台线程
backgroundThread.IsBackground = true;
//前、后台线程开始执行
foregroundThread.Start();
backgroundThread.Start();
}
负责工作内容的类:
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);
}
}
输出结果:
ForegroundThread count: 0
BackgroundThread count: 0
BackgroundThread count: 1
ForegroundThread count: 1
BackgroundThread count: 2
ForegroundThread count: 2
BackgroundThread count: 3
ForegroundThread count: 3
BackgroundThread count: 4
ForegroundThread count: 4
BackgroundThread count: 5
ForegroundThread count: 5
BackgroundThread count: 6
ForegroundThread count: 6
BackgroundThread count: 7
ForegroundThread count: 7
ForegroundThread count: 8
BackgroundThread count: 8
BackgroundThread count: 9
ForegroundThread count: 9
BackgroundThread count: 10
ForegroundThread finished counting.
请按任意键继续. . .
即:前台线程执行10次循环之后结束,进程随着前台线程的结束而结束,而不会理会后台线程的执行与否。