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();
Console.ReadKey();
}
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);
}
}
}
上面这段代码中,设定了threadTwo为后台线程,线程threadOne作为前台线程完成后程序应该结束并且后台线程被终结,结果应该是ThreadOne执行完程序结束,但是我在最后加了一句Console.ReadKey()之后,ThreadTwo会在ThreadOne完成之后继续执行到结束,请问是因为Console.ReadKey()是在前台线程中并没有被完成,所以让线程二继续运行下去吗?