控制台应用程序能否在完成其工作之前一直处于活动状态?

时间:2020-03-06 14:28:38  来源:igfitidea点击:

我刚刚阅读了Thread.IsBackground,如果我对它的理解正确的话,当它设置为false时,Thread是一个前台线程,这意味着它应该保持活动状态直到完成工作,即使该应用程序已经退出。出去。现在,我使用winform应用程序对其进行了测试,它可以按预期工作,但是与控制台应用程序一起使用时,该过程不会一直存在,而是立即退出。 " Thread.IsBackground"在控制台应用程序和Winform应用程序上的行为是否有所不同?

解决方案

我相信使用基于Winforms的应用程序,我们将获得一个单独的线程来处理消息传递,因此,如果"主"线程退出,我们仍然会有一个线程来保持该进程的生命。对于控制台应用程序,一旦主程序退出,除非我们启动了前台线程,否则该过程也会终止。

恕我直言,实际上,我们应该对应用程序的预期语义更加明确,并故意<thread> .Join。

Thread.IsBackground属性只标记,如果线程应该从退出阻塞进程。在某种形式的显式退出之前,保持线程处于活动状态不会产生任何魔力。

引用Thread.IsBackground属性MSDN(强调我的):

A thread is either a background thread or a foreground thread. Background threads are identical to foreground threads, except that background threads do not prevent a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.

为了使控制台应用程序保持活动状态,我们将需要进行某种循环,直到我们通过标志或者类似标志要求其停止运行为止。 Windows Forms应用程序具有内置的功能,因为它们具有消息泵功能(我相信)。