What is the proper procedure to alert a running thread to stop what it's doing and return before exiting the application?
protected Thread T;
protected static ManualResetEvent mre = new ManualResetEvent(false);
protected static bool ThreadRunning = true;
public Form1()
{
InitializeComponent();
T = new Thread(ThreadFunc);
T.Start();
}
private void ThreadFunc()
{
while (ThreadRunning)
{
// Do stuff
Thread.Sleep(40);
}
mre.Set();
}
private void ExitButton_Click(object sender, EventArgs e)
{
ThreadRunning = false;
mre.WaitOne();
mre.Close();
Application.Exit();
}
Initially I had my code setup like the above. My thinking for how exit properly is as follows:
- Set
ThreadRunning = false
so that the next time thread T checks that variable it knows to stop. - Call
mre.WaitOne()
to wait for thread T to say it's actually done via it callingmre.Set()
. - If so, then unblock and continue, dispose of mre (
mre.Close()
) and exit.
For some reason the above setup sometimes fails after the exit button is clicked and the whole form becomes inactive.
My new setup is below but doesn't seem entirely correct to me, for instance mre.Set()
isn't going to wait for anything and Application.Exit()
is immediately after it. I'm just waiting for it to fail like before, but so far it hasn't.
protected Thread T;
protected static ManualResetEvent mre = new ManualResetEvent(false);
protected static bool ThreadRunning = true;
public Form1()
{
InitializeComponent();
T = new Thread(ThreadFunc);
T.Start();
}
private void ThreadFunc()
{
while (ThreadRunning)
{
// Do stuff
Thread.Sleep(40);
}
mre.WaitOne();
mre.Close();
}
private void ExitButton_Click(object sender, EventArgs e)
{
ThreadRunning = false;
mre.Set();
Application.Exit();
}