这篇文章主要介绍一下前台线程后后台线程的区别:进程会等待前台线程结束后才能结束,而不会理会后台线程的执行状况。显示创建的线程默认情况下都是前台线程,除非手动设置 IsBackground = True。
using System;
using System.Threading;
namespace Chapter1.Recipe7
{
class Program
{
static void Main(string[] args)
{
var sampleForeground = new ThreadSample(10);
var sampleBackground = new ThreadSample(20);
var threadOne = new Thread(sampleForeground.CountNumbers);
threadOne.Name = "ForegroundThread";
var threadTwo = new Thread(sampleBackground.CountNumbers);
threadTwo.Name = "BackgroundThread";
threadTwo.IsBackground = true; //显示创建的线程都是前台线程,除非像这样将其设置为后台线程。
threadOne.Start();
threadTwo.Start();
}
class ThreadSample
{
private readonly int _iterations;
public ThreadSample(int iterations)
{
_iterations = iterations;
}
public void CountNumbers()
{
for (int i = 0; i < _iterations; i++)
{
Thread.Sleep(TimeSpan.FromSeconds(0.5));
Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i);
}
}
}
}
}
前台线程ForgroundThread会在打印10次后结束(stopped状态),从而结束整个main函数。而后台线程BackgroundThread只能跟着结束,虽然他只打印了10次而不是20次。