Simple question, to repeat the title:
Does closing the WinForms application stops all active BackgroundWorkers?
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.
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.
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.
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:
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.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With