2

I have the following code and the thread is not stoping even if i close the form or exit the program with System.Windows.Forms.Application.Exit();.

My code:

bool shouldStop = false; 

private void button1_Click(object sender, EventArgs e)
{
   backgroundThread = new Thread(
                      new ThreadStart(() =>
                      {    
                         for (int j = 0; j <= 1000; j++)
                         {
                            if (!shouldStop)
                            {
                               //do something
                            }

                            else
                            {
                               break;
                            }
                         }
                      }));
   backgroundThread.Start();
}

private void FormUpdateDB_FormClosing(object sender, FormClosingEventArgs e)
{
   shouldStop = true;
}
Brandon
  • 645
  • 5
  • 13
Christos K.
  • 99
  • 3
  • 14

2 Answers2

6

So first off, exiting from the application simply ends that thread's message loop. That won't directly tear down any other threads.

If you want the exiting of this application to end this other thread then all you need to do is make it a background thread. (Set the IsBackground property to true.) and the thread will be torn down when no other non-background threads are running.

As for why the thread keeps going after you set shouldStop to true, you are not properly synchronizing access to the variable. Because there is no memory barrier in place, the other thread is free to continue reading from a cached value of that variable, for as long as it wants to. While you could synchronize access yourself, you shouldn't try to. Instead, if it's important that this thread be a non-background thread (because it's doing something that cannot be stopped at some arbitrary point in time) then you should use a CancellationToken to cooperatively cancel another task. The implementation of that type properly synchronizes access to the data between threads.

Servy
  • 202,030
  • 26
  • 332
  • 449
  • I make my thread backgroundThread, so how should I stop it? With CancellationToken? – Christos K. May 05 '14 at 18:08
  • @ChristosK. As I described in my answer, when there are no non-background threads running the entire process will be torn down, taking all of the background threads to the abyss with it. A `CancellationToken` is only needed in the event that it's important for you to have a foreground thread. – Servy May 05 '14 at 18:09
1

Try adding

backgroundThread.IsBackground = true;

before the call to Start()

kcnygaard
  • 794
  • 7
  • 18