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);


private void someNameThread()
        //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;

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()));

- 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?

There is, but if I call it from the Main form it will just freeze the whole thing altogether, I mean I can replace all the whiles for the Join() which would be a better practice indeed, but would there be any way to loop through all running threads in my application without having to do a Join() manually for each of them?

The Mainform.Close(); was an older code I was trying, it was supposed to be Application.Exit(); (For others if they read it)