2

From here Does closing the application stops all active BackgroundWorkers? it seems not.

But from here How to stop BackgroundWorker on Form's Closing event? it seems yes.

So which is it?

(EDIT: I realize that the BackgroundWorkers 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?)

Community
  • 1
  • 1
ispiro
  • 26,556
  • 38
  • 136
  • 291
  • 1
    @Ramhound Did you see who answered the second question I reference? I don't lightly (or not lightly) ignore what he says. – ispiro Sep 12 '12 at 17:14

2 Answers2

4

Closing a Form does not stop all background workers started by that 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.

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.

Community
  • 1
  • 1
Servy
  • 202,030
  • 26
  • 332
  • 449
  • So you're saying that Hans' answer refers to a form that is not the main form? – ispiro Sep 12 '12 at 17:29
  • It applies to the main form too. – H H Sep 12 '12 at 17:32
  • @HenkHolterman So what does it matter if the BackgroundWorkers end with an exception? Is there a problem with that? – ispiro Sep 12 '12 at 17:33
  • 1
    Yes, you could lose data. Like the last lines in your logfile that would have told you about the deeper problem. – H H Sep 12 '12 at 17:35
  • @HenkHolterman OK. So it seems that the answer to my question is what you're saying - that the second link's answer is because he _does_ care that the `BackgroundWorker` exit gracefully. (You can turn your comment into an answer.) – ispiro Sep 12 '12 at 17:46
  • @ispiro I've added more information to the answer; the second link is more complex because it wants the background thread to exit gracefully. – Servy Sep 12 '12 at 17:48
1

Both of those links that you provide have the correct answer- BackgroundWorkers will be closed when the program is closed. Unmanaged resources are the ones you have to worry about explicitly closing.

MgSam
  • 12,139
  • 19
  • 64
  • 95