C#. NET foreground thread differs from background thread

Source: Internet
Author: User

This article from: http://www.cnblogs.com/zfanlong1314/archive/2012/02/26/2390455.html

. The common language runtime (Common Language runtime,clr) of net can differentiate between two different types of threads: foreground and background threads. The difference between the two is that the application must run out of all foreground threads to exit, and for a background thread, the application can exit without considering whether it has finished running, and all background threads will automatically end when the application exits.

. NET environment uses thread to establish threads by default is the foreground thread, that is, the thread property Isbackground=false, in the process, as long as there is a foreground thread that does not exit, Processwill not be terminated. The main thread is a foreground threading. The background thread terminates automatically, regardless of whether the thread ends, as long as all foreground threads exit (including normal exit and exception exit). A generic background thread is used to handle short-time tasks, such as using a background thread in a Web server to handle request information sent by the client. The foreground thread is typically used to handle tasks that require long waits, such as a program that listens to client requests in a Web server, or a program that periodically scans certain system resources. conceptual issues that need to be understood: The thread is pinned on the process, the process is over, and the thread is no longer there! as long as there is a foreground thread not exiting, the process will not terminate! That is, the program will not be closed! (That is, you can see in the explorer that the process is not finished.) )
Test code:

publicpartialclassForm1 : Form   {       publicForm1()       {           InitializeComponent();       }       /// <summary>       /// 弹出窗体Form2       /// </summary>       /// <param name="sender"></param>       /// <param name="e"></param>       privatevoidbutton1_Click(objectsender, EventArgs e)       {           Form2 _frm2 = new Form2();           _frm2.Show();       }         }publicpartialclassForm2 : Form   {       publicForm2()       {           InitializeComponent();       }       Thread _Thread = null;       privatevoidForm2_Load(objectsender, EventArgs e)       {           _Thread = newThread(() => { while(true) { /*制造无限循环,等待用户关闭线程*/} });           _Thread.IsBackground = false;//false:设置为前台线程<span style="color: #ff0000;"><strong>,系统默认为前台线程</strong></span>。            //_Thread.IsBackground = true;//true:后台线程            _Thread.Start();       }   }
Test Result: Note In debug mode, see if VS is OFF!!! Or, in Realse mode, see if the application thread in the Explorer is closed.

If you set the foreground thread, which is IsBackground = False, close form 2, and close Form 1, while Form 1 is closed, the application remains in the resource manager.
If you set the background thread, which is IsBackground = True, after you close form 1, the application ends immediately from the resource manager.

Additional notes:

private voidForm2_Load(objectsender, EventArgs e)       {           Thread _Thread = newThread(() =>           {               for(inti = 0; i < 10; i++)               {                   //前台线程:正常情况下,关闭主线程的时候,会等待前台线程执行完成里面的代码后才退出进程。                   //本例子中虽然模拟了在循环中线程暂停1000ms,但是由于关闭当前Form2窗体,窗体对象已经释放了,                   //然而在前台线程中有操作界面UI的代码,此时已经无效了;因为窗体对象已经释放了,前台线程也会无效即自动退出了;即这种情况关闭主线程的时候,程序最多只会等待 Thread.Sleep(1000)就会退出。                   this.BeginInvoke(newMethodInvoker(() => { this.Text = ""; }));                   Thread.Sleep(1000);//注意此处的Thread.Sleep还是主线程。               }           });           _Thread.IsBackground = false;//false:设置为前台线程<span style="color: #ff0000;"><strong>,系统默认为前台线程</strong></span>。            //_Thread.IsBackground = true;//true:后台线程            _Thread.Start();       }

C#. NET foreground thread differs from background thread

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.