A button on the parent form is used to start the thread. If the parent form is closed in the development environment the thread keeps running in the background preventing edits to the source code on a 64 bit Windows 7 platform. The thread has to be killed by Menu > Debug > Stop Debugging. What is the proper way to programmatically kill the thread when the parent Form is closed?
private void buttonW_Click(object sender, EventArgs e) { Thread t = new Thread(Main.MyThread); t.Start(); } private static void MyThread() { ... }
Calling the exit subroutine terminates the entire process, including all its threads. In a multithreaded program, the exit subroutine should only be used when the entire process needs to be terminated; for example, in the case of an unrecoverable error.
Modern ways to suspend/stop a thread are by using a boolean flag and Thread. interrupt() method. Using a boolean flag: We can define a boolean variable which is used for stopping/killing threads say 'exit'. Whenever we want to stop a thread, the 'exit' variable will be set to true.
Exiting the main thread will not result in the process exiting if there are any other threads still active. According to the old-fashioned model of how processes exit, a process was in control of all its threads and could mediate the shutdown of those threads, thereby controlling the shutdown of the process.
If you make your worker threads daemon threads, they will die when all your non-daemon threads (e.g. the main thread) have exited. Thanks for the simple and precise answer, the default threading. Thread daemon status isDaemon() is False, set it True by setDaemon(True) . This answers the question and just works.
If you want the app to exit when the main thread has finished, you can just make the new thread a background thread:
Thread t = new Thread(Main.MyThread); t.IsBackground = true; t.Start();
Basically the process will exit when all the foreground threads have exited.
Note that this could be bad news if the background thread is writing a file when the form is closed, or something similar...
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