gnychis
gnychis

Reputation: 7555

Why background thread not exiting when form closes?

As I understand it, if I set _myThread.isBackground = true then the thread should exit when the form is closed. Unfortunately I'm not finding that my thread is exiting. Here is what my code looks like:

private void MainForm_Load(object sender, EventArgs e)
{
    // <snip>
    daemon = new Daemon();
    // <snip>
}

public Daemon()
{
    // Start the main thread which will do most of the connection checking and work
    _mainThread = new Thread(() => MainThread(this));
    _mainThread.IsBackground = true;
    _mainThread.Start();
}

/// <summary>
/// This is the work that the main thread does.
/// </summary>
private void MainThread(Daemon daemon)
{
    while(true)
    {
        try
        {
            // Do things.
            Thread.Sleep(2000);            // Sleep for a bit to not hammer.
        }
        catch (Exception e)
        {
            Logger.Exception(e);
        }
    }
}

I thought that since the thread is started from the form that setting isBackground=true would force it to close on form exit.

Am I missing or misinterpreting something?

Upvotes: 2

Views: 2673

Answers (3)

Fabjan
Fabjan

Reputation: 13676

IsBackground = true means that when main thread ended (and all other non-background threads) - it'll stop. But what are these threads ? I believe when you close your mainform you still have one non-background thread running may be one where this form was created and ititialized.

Upvotes: 0

Servy
Servy

Reputation: 203823

Strictly speaking that the thread is a background thread prevents it from keeping the process alive. The process will stick around for as long as there is at least one non-background thread running. The UI thread is a non-background thread, and by default in a winform application closing the main thread will result in that thread completing.

So now that we have all of this we can see that, often enough, closing the main form will "kill" background processes, but there are any number of things that can stop this.

The main thread ending doesn't necessarily mean the application will end, and the UI thread will terminate. One can adjust the behavior of the application to end under different criteria, or add code to run in Main after the application finishes running.

You can also create additional non-UI threads, and if you do, they'll keep the entire process (and all of the background threads) alive.

Upvotes: 3

Dialecticus
Dialecticus

Reputation: 16761

According to documentation background thread just wont prevent the process from terminating. There is no guarantee that the thread will finish "nicely", whatever that may mean.

Upvotes: 2

Related Questions