. Net Common Language Runtime (CLR) can distinguish two different types of threads: foreground thread and background thread. The difference between the two is that the application can exit only after running all the foreground threads. For background threads, the application can exit without considering whether it has been completed, all background threads automatically end when the application exits.
By default, a Thread created using Thread in the. Net environment is a foreground Thread, that is, the Thread attribute IsBackground = false. In the process, the process will not be terminated if a foreground Thread does not exit. The main thread is a foreground thread. The background thread automatically terminates after all foreground threads exit (including normal and abnormal exits), regardless of whether the thread ends. Generally, backend threads are used to process short tasks. For example, in a Web server, backend threads can be used to process the request information sent from the client. Foreground threads are generally used to process tasks that require a long wait, such as programs that listen to client requests on Web servers or programs that regularly scan certain system resources.
Test code:
C # Code:
Public partial class Form1: Form
{
Thread _ Thread = null;
Public Form1 ()
{
InitializeComponent ();
}
// Test the foreground thread and background thread
Private void button#click (object sender, EventArgs e)
{
_ Thread = new Thread () =>{ while (true) {/* create an infinite loop and wait for the user to close the Thread */}});
_ Thread. IsBackground = false; // false: it is set to the foreground Thread, and the system defaults to the foreground Thread.
// _ Thread. IsBackground = true; // true: Background Thread
_ Thread. Start ();
}
Private void button2_Click (object sender, EventArgs e)
{
_ Thread. Abort ();
}
}
Test results: Check whether vs is disabled in Debug mode !!! You can also view whether the application thread in [Resource Manager] is closed in Realse mode.
If it is set to a foreground thread, that is, IsBackground = False, the program is still running after the X close button of the form is clicked.
If it is set to a background thread, that is, IsBackground = True, the program exits immediately after the X close button of the form is clicked.