Search code examples
c#backgroundworker

Do I have to close running BackgroundWorkers when user closes form?


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?)


Solution

  • 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.