views:

334

answers:

8

Simple question, to repeat the title:

Does closing the WinForms application stops all active BackgroundWorkers?

(I know that many StackOverflow's threads talk about BackgroundWorker, but none I've searched gave an explicit answer)...

A: 

If the application completely closes (as in nothing is preventing it from shutting down) your background workers will also be gone.

BennyM
That's kind of a circular answer. If the background workers aren't stopped automatically when the app is closing, they will prevent the application from closing.
Lasse V. Karlsen
A: 

I think yes. Because threads are associated with process and if the process is closed all threads has to end.

Ismail
A: 

Once the process is gone all associated threads are gone as well.

dkackman
Except if their `IsBackground` property is set to `false`.
Groo
Which would prevent the process from terminating. So the answer holds ;)
dkackman
+11  A: 

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.

Sources: Reflector, Delegate.BeginInvoke, MSDN on Thread Pooling, Thread.IsBackground

Groo
+5  A: 

BackgroundWorker threads are background threads (ThreadPool threads), which die when the application dies.

Will
+6  A: 

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.

Yann Schwartz
A: 

First of all, just to make this answer simple:

When a process has closed, all of its threads have terminated. There's no question about this.

The question, as I interpret it, thus becomes:

Will still-running BackgroundWorker instances prevent an application from closing?

The answer to that question is: No, they won't.

Lasse V. Karlsen
+1  A: 

Yes, it will. I wrote this simple form, and closing the form exits the application:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.backgroundWorker1.RunWorkerAsync();
    }

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        while (true)
        {
            Thread.Sleep(100);
        }
    }
}
Philip Wallace