Reputation: 99
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;
}
Upvotes: 2
Views: 204
Reputation: 203802
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.
Upvotes: 6
Reputation: 814
Try adding
backgroundThread.IsBackground = true;
before the call to Start()
Upvotes: 1