[英]Do I have to close running BackgroundWorkers when user closes form?
From here Does closing the application stops all active BackgroundWorkers? 从这里关闭应用程序是否会停止所有活动的BackgroundWorkers? it seems not.
似乎没有。
But from here How to stop BackgroundWorker on Form's Closing event? 但是从这里如何在Form的Closing事件中停止BackgroundWorker? it seems yes.
好像是。
So which is it? 那是什么呢?
(EDIT: I realize that the BackgroundWorker
s might exit with an exception. But what's the problem with that? Isn't the point here to not leave running threads which take up resources?) (编辑:我意识到
BackgroundWorker
可能会异常退出。但这是什么问题?这里的重点是不要不让正在运行的线程占用资源吗?)
Closing a Form
does not stop all background workers started by that form. 关闭
Form
不停止该表格启动的所有后台工作人员。
When the entire application ends it will stop all background threads. 当整个应用程序结束时, 它将停止所有后台线程。
Closing the main form (unless you have modified the Main
method to do something else) will end the entire application. 关闭主窗体(除非您已修改
Main
方法以执行其他操作)将结束整个应用程序。
Each question you referenced is correct for what it says. 您引用的每个问题都是正确的。 If you close the main form, then the entire application will end and the background worker will be closed on its own.
如果关闭主窗体,则整个应用程序将结束,后台工作程序将自行关闭。 If the form that is closing isn't the main form, but some other form, and you want the background worker that it starts to be stopped, then you will need to do so yourself.
如果要关闭的窗体不是主要窗体,而是其他窗体,并且您希望后台工作人员开始停止它,那么您需要自己这样做。
It's also worth noting that the second link that you have provided asks for something a bit more complex. 还值得注意的是,您提供的第二个链接要求更复杂的内容。 It's clear in that post that closing the form (if it's the main form) will stop execution of the background thread.
在那篇文章中很明显,关闭表单(如果是主表单)将停止执行后台线程。 What the OP is trying to do there is to tell the background thread, "hey, it's time to finish up, we're done here" and then have the form wait until that background thread can finish cleaning things up nicely, rather than just exiting and forcibly aborting the thread while it's in the middle of doing something.
OP试图在其中做的是告诉后台线程“嘿,是时候结束了,我们在这里完成了”,然后让表单等待直到后台线程可以很好地完成清理工作,而不仅仅是在执行某项操作时退出并强行中止该线程。
Both of those links that you provide have the correct answer- BackgroundWorker
s will be closed when the program is closed. 您提供的两个链接都具有正确的答案-程序关闭时,将会关闭
BackgroundWorker
。 Unmanaged resources are the ones you have to worry about explicitly closing. 非托管资源是您必须担心显式关闭的资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.