我在 GUI 中运行一些后台线程。目前我正在实现一个个人线程取消代码,但线程中有 IsBackground 属性,根据 MSDN,他们将自行取消。
我知道它会去 Thread.Abort() ,这很糟糕,但在这个后台线程中没有任何东西需要保持适当的状态或需要适当的清理。
如果用户只是在后台线程中间关闭应用程序,我会尝试避免任何崩溃。由于多线程场景很难测试,我想了解您对这个主题的看法。
基本上,不是滚动我自己的代码,我应该只设置 IsBackground = True 而忘记其余的?
最佳答案
MSDN page在 IsBackground
属性(property)状态:
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.
所以这对我来说意味着你必须让你的线程非常具有防御性,以确保它没有打开任何连接,数据库写一半等等。任何关键的东西都需要在前台线程中,以防止应用程序关闭直到它完成。
关于.net - 当应用程序终止时,我可以安全地依赖线程中的 IsBackground 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1354196/