How to exit all running threads?

The following code does not exit the application. How can I exit the application and make sure all the running threads are closed?

foreach (Form form in Application.OpenForms)
{
form.Close();
}
Application.Exit();
109820 次浏览

You don't show the use of any threads in your code, but let's suppose you do have threads in it. To close all your threads you should set all of them to background threads before you start them, then they will be closed automatically when the application exits, e.g.:

Thread myThread = new Thread(...);
myThread.IsBackground = true; // <-- Set your thread to background
myThread.Start(...);

A "HOWTO: Stop Multiple Threads" article from microsoft: http://msdn.microsoft.com/en-us/library/aa457093.aspx

You can try the following code:

Environment.Exit(Environment.ExitCode);

This should work for all threads you opened.

protected override void OnExiting(Object sender, EventArgs args)
{
base.OnExiting(sender, args);
Environment.Exit(Environment.ExitCode);
}

I went through a similar issue in my software, but unfortunately just making the threads to work in background didn't solve the issue. In fact while the thread brings back data (the main software is data driven) and if I close the application, it results to Windows Error, giving rise to a debugging message.

So what actually worked for me:

Step 1: Made all threads run in background such as

Thread aThread = new Thread(MethodName);
aThread.IsBackground = true; //<-- Set the thread to work in background
aThread.Start();

Step 2: In the closing action of the form/application call the Environment.Exit method, such as

Environment.Exit(Environment.ExitCode);

This kept the memory managed perfectly, with no memory leak.

Hope this helps.

This got the job done for me:

Instead of using:

Application.Exit()

which leaves other threads open, try using:

Environment.Exit(Environment.ExitCode);

This is the best way to make sure that your application closes (forcefully):

(Process.GetCurrentProcess()).Kill()

The problem with Environment.Exit is that it does not work unless it is on the main thread. Also, it sometimes thread locks.

The main reason that your program is not closing properly is because the form is not able to dispose itself (and thus all object that it created). Fixing this is much more difficult. I would recommend running the above code after waiting a while for any possible dispose handlers to get called first.

I puzzled with this for a while as the common answer is to make the threads you call mythread.IsBackground = true;

The common answer to run a thread is to use a while loop with a flag

while(!exitflag)
{
// thread running
}

When User presses the eXit forms button Visual studio still is running the threads but the form closes. I used the Form Closing event to set the exitcode flag and then wait for the threads to close.

I have a single form using a Timer and two additional threads, One collects streaming data and the other does calculations on that data and saves to an sql table. Data collection is collected in a circular buffer. I use two static bool values as flags where the threads set the flag to true or false using mythread.Isalive as the Form Closing event does not have access to the thread handles.

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
Debug.WriteLine("Form Closing Event");
exitFlag = true;
int ThreadsClosed = 0;
while (ThreadsClosed < 2)
{
ThreadsClosed = 2;
if (ProcessDataAlive) ThreadsClosed = 0;
if (StreamingDataAlive) ThreadsClosed = 0;
Application.DoEvents();
}
Debug.WriteLine("Threads are all closed");
Thread.Sleep(5000); // allow debug window open to read remove for release
}