How to exit all running threads?

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

foreach (Form form in Application.OpenForms) { form.Close(); } Application.Exit(); 
+41
multithreading c # winforms
Apr 22 '10 at 7:24
source share
5 answers

You do not show the use of any threads in the code, but suppose that there are threads in it. To close all your threads, you must install all of them in the background thread before starting them, then they will be automatically closed when the application exits, for example:

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

"HOWTO article: Stop multiple threads" from Microsoft: http://msdn.microsoft.com/en-us/library/aa457093.aspx

+68
Apr 22 2018-10-22T00:
source share

You can try the following code:

 Environment.Exit(Environment.ExitCode); 
+44
Apr 20 '13 at 17:34
source share

This should work for all threads that you have opened.

 protected override void OnExiting(Object sender, EventArgs args) { base.OnExiting(sender, args); Environment.Exit(Environment.ExitCode); } 
+12
Sep 29 '13 at 21:54
source share

I went through a similar problem in my software, but unfortunately, just forcing the threads to run in the background, this did not solve the problem. In fact, when the stream returns data (the main software is data driven), and if I close the application, it will result in a Windows error, which will lead to debugging of the message.

So what actually worked for me:

Step 1: Made all the threads in the background, e.g.

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

Step 2: In the final form / application action, the Environment.Exit method is called, for example

 Environment.Exit(Environment.ExitCode); 

This ensured that the memory worked correctly without memory leak.

Hope this helps.

+9
Jun 02 '17 at 14:51
source share

This did the job for me:

Instead of using:

 Application.Exit() 

which opens other threads, try using:

 Environment.Exit(Environment.ExitCode); 
+1
Jul 25 '17 at 15:31
source share



All Articles