前台线程:在主线程运行结束后,若前台线程没有运行完则会阻止主线程的关闭 后台线程:在主线程运行结束后,整个线程会结束
代码语言:javascript复制 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);
}
}
}
static void Main(string[] args)
{
var sampleForeground = new ThreadSample(10);
var sampleBackground = new ThreadSample(20);
var threadOne = new Thread(sampleForeground.CountNumbers);
threadOne.Name = "ForgroundThread";
var threadTwo = new Thread(sampleBackground.CountNumbers);
threadTwo.Name = "BackgroundThread";
threadTwo.IsBackground = true;
threadOne.Start();
threadTwo.Start();
}
这里threadTwo为后台线程则treadOne运行结束后则整个线程退出,若不设置为前台线程则会一直运行到threadOne和threadTwo都结束。