我刚刚阅读了Thread.IsBackground
,如果我理解正确的话,当它设置为false
时,线程是前台线程,这意味着它应该保留即使应用程序已退出,它仍然存在,直到它完成工作。现在我用 winform 应用程序对此进行了测试,它按预期工作,但是当与控制台应用程序一起使用时,该进程不会保持事件状态,而是立即退出。 Thread.IsBackground
的行为与控制台应用程序和 winform 应用程序不同吗?
最佳答案
Thread.IsBackground
属性仅标记线程是否应阻止进程退出。它不会执行任何魔法来保持线程处于事件状态,直到某种显式退出为止。
引用Thread.IsBackground Property 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 窗体应用程序由于其消息泵而内置了此功能(我相信)。
关于.net - 控制台应用程序可以在完成工作之前保持事件状态吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/107154/