请考虑以下代码。
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()
来防止主线程在其他衍生线程结束之前结束?
答案 0 :(得分:3)
存在一些差异,但回答您问题的重要部分是线程池使用后台线程,这些不会阻止现有进程。您可以阅读更多here。
答案 1 :(得分:-1)
t.wait() 在任务已经启动后无法使用。