Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill Thread on exit?

Tags:

c#

winforms

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() {     ... } 
like image 220
jacknad Avatar asked May 19 '11 17:05

jacknad


People also ask

Does exit kill all threads?

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.

How do I kill a specific thread?

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.

What happens to threads on exit?

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.

How do you end a thread when the main program ends?

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.


1 Answers

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...

like image 111
Jon Skeet Avatar answered Sep 21 '22 08:09

Jon Skeet