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; //如果讲这行代码注释,那程序就会输出20次
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(500);
Console.WriteLine("{0}输出:{1}",Thread.CurrentThread.Name,i);
}
}
}
这里定义了一个前台线程和后台线程,执行这段代码,程序将输出10次。
如果将第二个线程也改成前台线程,那么程序将输出20次。
所以前台线程和后台线程的区别就是,当前台线程完成后,后台线程哪怕还没有完成也会被终结。