Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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(); 
like image 311
monkey_boys Avatar asked Apr 22 '10 07:04

monkey_boys


People also ask

How do I cancel all threads?

A thread can also explicitly terminate itself or terminate any other thread in the process, using a mechanism called cancelation. Because all threads share the same data space, a thread must perform cleanup operations at termination time; the threads library provides cleanup handlers for this purpose.

Does exit kill all threads?

Calling exit while other threads are still running will likely result in a crash. No C++ cleanup will be done. as @πάνταῥεῖ says you need to join all other threads before shutting down.

How do you end all threads in C++?

In short: You can't kill threads in ISO c++. You can only e.g. repeatedly poll a flag inside the thread and stop further processing. As std::threads are usually implemented on top of pthreads on linux, you might be able to leverage that API, e.g. have a look at pthread_cancel.


1 Answers

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

like image 146
Kiril Avatar answered Oct 06 '22 20:10

Kiril