Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does closing the application stops all active BackgroundWorkers?

Simple question, to repeat the title:

Does closing the WinForms application stops all active BackgroundWorkers?

like image 528
Kornelije Petak Avatar asked Nov 06 '09 13:11

Kornelije Petak


People also ask

How do I stop DoWork BackgroundWorker?

CancelAsync doesn't actually abort your thread or anything like that. It sends a message to the worker thread that work should be cancelled via BackgroundWorker. CancellationPending . Your DoWork delegate that is being run in the background must periodically check this property and handle the cancellation itself.

What is BackgroundWorker?

The BackgroundWorker class allows you to run an operation on a separate, dedicated thread. Time-consuming operations like downloads and database transactions can cause your user interface (UI) to seem as though it has stopped responding while they are running.

Is BackgroundWorker threaded?

BackgroundWorker, is a component in . NET Framework, that allows executing code as a separate thread and then report progress and completion back to the UI.


2 Answers

Yes, it does.

BackgroundWorker.RunWorkerAsync simply calls BeginInvoke on a internal delegate, which in turn queues the request to the ThreadPool. Since all ThreadPool threads are background, yes, it will end when the application ends.

However, keep in mind that:

  1. By "closing the WinForms application" I am presuming closing the main Form instance (that's generally the one passed to Application.Run in the Program class autogenerated by Visual Studio). If you have a child window with a background worker, it will not stop its BackgroundWorker automatically.

  2. Letting a background thread be aborted on application exit is not the recommended way to end the thread, as you have no guarantees where it will be aborted. A much better way would be to signal the worker before closing, wait for it to finish gracefully, and then exit.

More info: Delegate.BeginInvoke, MSDN on Thread Pooling, Thread.IsBackground

like image 183
Groo Avatar answered Sep 26 '22 02:09

Groo


The only way a thread can go on executing after your main (UI) thread has stopped is if it has been created explicitely, by creating a new Thread instance and setting the IsBackground to false. If you don't (or if you use the ThreadPool which spawns background threads - or the BackgroundWorker which also uses the ThreadPool internally) your thread will be a background thread and will be terminated when the main thread ends.

like image 36
Yann Schwartz Avatar answered Sep 27 '22 02:09

Yann Schwartz