考虑下面的代码。
线程
static void Main(string[] args)
{
Thread t = new Thread(Foo);
t.Start();
Console.WriteLine("Main ends.");
//t.Join();
}
static void Foo()
{
for (int x = 0; x < 1000000000; x++) ;
Console.WriteLine("Foo ends.");
}
任务
static void Main(string[] args)
{
Task t = new Task (Foo);
t.Start();
Console.WriteLine("Main ends.");
t.Wait();
}
static void Foo()
{
for (int x = 0; x < 1000000000; x++) ;
Console.WriteLine("Foo ends.");
}
当使用
Task
时,我们需要t.Wait()
来等待线程池线程完成后再结束主线程;但是当使用Thread
时,我们不需要t.Join()
就可以达到同样的效果。问题:为什么不需要
t.Join()
来防止主线程在其他已生成的线程结束前结束?
IsBackground
属性设置为true,然后再次进行测试。 - L.B