"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 74: Beware of thread IsBackground

Source: Internet
Author: User

Recommendation 74: Beware of thread IsBackground

In the CLR, threads are divided into foreground and background threads, that is, each thread has a IsBackground property. The only difference between the two expressions is that if the foreground thread does not exit, the application's process will persist and all foreground threads must exit before the application exits. The background process does not have this limitation, and if the application exits, the background thread will also exit.

View the following code:

Static voidMain (string[] args) {Thread T=NewThread (() ={Console.WriteLine ("The thread begins to work ..."); //Omit work CodeConsole.readkey (); Console.WriteLine ("Thread End");      }); //Note that the default is FalseT.isbackground =false;      T.start (); Console.WriteLine ("Main thread Complete"); } 

Threads created with thread default to the foreground thread, that is, the IsBackground property defaults to False. The above code needs to wait until the end of the work (typing a button) the application will not end, and if set IsBackground is true, the application will end immediately.

The demo code uses thread, but we should note that threads in the thread pool are the background threads by default.

Based on the difference between the front and back threads, you should use the background thread more in the actual encoding. The foreground thread is used only in very critical work, such as when a thread is executing a transaction or some unmanaged resource in possession needs to be freed.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

"Go" writing high-quality Code 157 recommendations for improving C # programs--Recommendation 74: Beware of thread IsBackground

Related Article

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.