The first time I used thread-related things, I encountered a very "strange" problem. Program (Or the main thread) has ended, but the whole program does not exit, it depends on the process list! I have never encountered this problem before, and this program is the first time I use the thread (, ). The problem must be found here, so I wrote a console program for verification, Code As follows: 1 Using System;
2 Using System. Collections. Generic;
3 Using System. text;
4 Using System. net;
5 Using System. net. Sockets;
6 Using System. Threading;
7
8 Namespace Test
9 {
10 Class Program
11 {
12 Static Void Main ( String [] ARGs)
13 {
14 Thread testthread = New Thread ( New Threadstart (program. testthread ));
15 Testthread. Name = " Testthread " ;
16 Testthread. Start ();
17 }
18
19 Static Void Testthread ()
20 {
21 While ( True )
22 {
23 Thread. Sleep ( 0 );
24 }
25 }
26 }
27 }
28
Run the above example. Because the thread testthread is an endless loop, this thread will not exit. However, my expectation is that once the main thread ends, it means that the program is about to exit, then the auxiliary threads should be automatically terminated. But it is obvious from the experiment code running result that the process will continue to run as long as any active thread exists!
To solve this problem, add a line at the end of the main function: 1 Testthread. Abort ();
Then everything is normal, but I feel a little bit redundant, and I don't understand why the system can automatically help us do this, are there any unpredictable adverse consequences ???
// Update
Correction: The program cannot exit as long as any "foreground" thread is running.