为什么 Main 在旋转新线程时等待,但任务却不是这样

Why Main waits when spinning a new thread, but not so with a task

我想知道为什么在控制台应用程序中,如果我从 Main 旋转一个新线程到 运行,即使 Main 将到达终点它也会等待,但如果我旋转一个新任务,它会退出而不是等待任务结束。

例如

static void Main(string[] args) 
{
    Thread t = new Thread(new ThreadStart(SomeMethod));
    t.Start();            
    // Main will wait, and app won't close until SomeMethod finishes
}

对比

static void Main(string[] args)
{
    Task.Run(() => SomeMethod());
    // Main will close / app shuts down without waiting for SomeMethod to finish
}

您已在另一个线程上将 SomeMethod 设置为 运行,因此它现在是异步的。您不需要等待结果,所以 Main 将继续并退出,杀死进程中的两个线程。

使用:

Task.Run(async () => await SomeMethod());

假设 SomeMethod 是可等待的,否则你可以在外部等待结果

Task.Run(() => SomeMethod()).Result;

阅读 Thread.IsBackground 属性 的文档时,您会注意到有两种类型的线程,后台线程和前台线程:

... background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated... any remaining background threads are stopped and do not complete.

Thread 构造函数阻止 Main 进程终止的原因是因为默认情况下,它会创建前台线程,而基于任务的异步操作会自动在 ThreadPool 上执行,它默认使用后台线程,并允许进程在完成之前终止。