应用程序关闭时线程不会中止
我有一个应用程序,它在单独的线程中执行一些后台任务(网络监听和读取)。然而,当我关闭应用程序时(单击标题栏上的“x”按钮),线程似乎没有被终止/中止。 这是因为主线程例程是 while(true) {...}
吗? 这里的解决方案是什么?我正在寻找线程的一些“中断”标志作为“while”循环的条件,但没有找到任何标志。
I have an application which does some background task (network listening & reading) in a separate Thread
. It seems however that the Thread is not being Terminated/Aborted when I close the application (click "x" button on titlebar).
Is that because the main Thread routine is while(true) {...}
?
What is the solution here? I was looking for some "interruption" flag for the Thread as the condition for "while" loop, but didn't found any.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
最简单的方法是设置 IsBackground 属性线程为 true。这将阻止它保持应用程序打开。当所有非后台线程终止时,应用程序终止。
停止线程的一种更受控制的方法是向其发送一条消息以彻底关闭,并确保在让主线程终止之前它已终止。
我不推荐的方法是调用
Thread.Abort
。这有很多问题,其中之一是不能保证终止线程。从文档中:
强调我的。
The simplest way is to set the IsBackground property of the thread to true. This will prevent it from keeping the application open. An application terminates when all non-background threads terminate.
A more controlled way to stop the thread is to send it a message to shut down cleanly and ensure that it has terminated before letting your main thread terminate.
A method that I wouldn't recommend is to call
Thread.Abort
. This has a number of problems, one of which is that it is not guaranteed to terminate the thread. From the documentation:Emphasis mine.
您始终可以强制解决该问题:
更好的方法是将 Thread.IsBackground 属性设置为 true,正如 Mark 已经提到的那样。
You can always force the issue:
The better approach is to set the Thread.IsBackground property to true as Mark already mentioned.
您可以将 while(true) 循环改进为
更优雅一点,缩短标识符名称。
You could improve the while(true) loop to
A bit more graceful, short from the identifier names.
好吧,也许您应该:而不是
while(true)
,并且,在表单的关闭事件中,
最后一行只是为了确保您等待线程干净地完成。有许多其他方法可以强制结束线程,但问题就在那里:您不想强制事情,您希望它们尽可能自然地发生。
连接后,您可以检查线程的状态以查看其是否已完成。如果没有,然后(并且只有在那时)通过中止强制其完成,并且可能通知您的用户(或写入日志记录)某些内容尚未按应有的方式结束。
Well, instead of
while(true)
, maybe you should:And, at the closing event for your form,
where the last line is just to make sure you wait for the thread to cleanly finish. There are many other ways to force an end to a thread, but the problem is just there: you don't want to be forcing things, you want them to happen as naturally as possible.
After the join, you can check the status of thread to see if it has finished. If it doesn't, then (and only then) force its finish with a abort, and maybe notify your user (or write a log record) that something has not ended the way it should.
您可以将线程启动为:
它将随着应用程序关闭而自动中止。
You can start your thread as:
And it will be abort automatically with application close.