.net - 控制台应用程序可以在完成工作之前保持事件状态吗?

标签 .net multithreading

我刚刚阅读了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/

相关文章:

c# - 在 foreach(单词中的字符串单词)中,如果 (if->true) C#,我如何转到下一个单词?

c# - 如何正确并行化严重依赖 I/O 的作业

java - prolog 错误中出现意外的 EOF

.net - 使用C#中的任务并行库,每个处理器运行一个并行任务

C# VS 卸载程序

c# - System.ArgumentNullException 与 NetMQ.Msg.Put()

c# - System.Timers.Timer 非常不准确

java - 在内部类中访问 for 循环变量

java - 在 Java 中运行多个线程

ios - 如何在 iOS 中实现多线程?