JT9
JT9

Reputation: 944

Does a background thread end when a C# form closes?

I have a C# application using the .NET Compact Framework 3.5 that opens multiple forms depending on the user interaction. In one particular form, I have a background thread that periodically checks the battery life of the Windows CE device the application runs on. Note, this is not the form called in Main(). For example, Application.Run(new MyOtherForm()); is called in Main().

public MyForm()
{
    Thread mythread = new Thread(checkBatteryLife);
    mythread.IsBackground = true;
    mythread.Start();
}

private void checkBatteryLife()
{
    while(true)
    {
        // Get battery life

        Thread.Sleep(1000);
    }
}

My question is, when MyForm closes, does the background thread stop as well? Or will it stop when the application exists (when Main() finishes processing)? If the background threads ends when the application closes, I found this workaround, but seems unnecessary if the thread stops at the time the form closes.

EDIT: I opted to use a System.Threading.Timer instead of a Thread.

private System.Threading.Timer batteryLifeTimer;

public MyForm()
{
    AutoResetEvent autoEvent = new AutoResetEvent(false);
    TimerCallback tcb = checkBatteryLife;
    this.batteryLifeTimer = new System.Threading.Timer(tcb, autoEvent, 1000, 10000);
}

private void checkBatteryLife(Object stateInfo)
{
    // Get battery life.
    // Update UI if battery life percent changed.
}

private void MyForm_Closing(object sender, CancelEventArgs e)
{
    this.batteryLifeTimer.Dispose();
}

Upvotes: 0

Views: 798

Answers (1)

Servy
Servy

Reputation: 203823

The background thread will stop executing when it either finishes executing the delegate, or when there are no more foreground threads in the entire process.

Upvotes: 4

Related Questions