C # thread: As long as any thread is running, the program will not exit ?!

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.