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();
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With