Hi, I got multiple threads in different classes created in this manner:
private ThreadStart someName_TS;
public Thread someName_Thread;
public void someName()
{
someName_TS = new ThreadStart(someNameThread);
someName_Thread = new Thread(someName_TS);
someName_Thread.Start();}
}
private void someNameThread()
{
while(!Shutdown)
{
//Do heavy work
}
}
The heavy work is set to a "while" statement that is always set to false unless the user wants to close the application.
Now on my main form I got the following FormClosing code:
if (e.CloseReason == CloseReason.UserClosing)
{
e.Cancel = true;
guiThread.closeApp();
}
Now where I think I need help is that I just made a new thread to wait for everything else to finish to then close, this is the closing thread:
Shutdown = true;
//Wait for all threads to safely finish
//finish before exiting
//Check if classes were ever initialized
if (Mainform.threadOneClassName != null)
{
//Loop until task is done
while (Mainform.threadOneClassName.randomThreadNameOne.IsAlive){ }
}
if (Mainform.threadTwoClassName != null)
{
while (Mainform.threadTwoClassName.randomThreadNameTwo.IsAlive){ }
}
if (Mainform.threadThreeClassName != null)
{
while (Mainform.threadThreeClassName.randomThreadNameThree.IsAlive){ }
}
//Close main form (The reason wont be UserClosing)
Mainform.Invoke(new Action(() => Mainform.Close()));
Steps-by-Steps:
- The application was cancelled from closing if the user tried to close it
- Starts a new thread to handle the closing
- The new thread sets Shutdown to true
- Sets "while"s statements for each thread to make sure they aren't "alive" anymore
- Closes the main form.
The code itself works, but I like learning better and efficient ways for future references, is there any easier/simple way to stop threads when the application is closing?