c#多线程中(前台线程与后台线程的区别)
我不想多说废话,直接,将代码copy到一个winform程序中去感受一下吧!
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Threading; namespace IsbackGround { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void DoWork() { for (int i = 0; i < 5; i++) { MessageBox.Show("我擦"); Thread.Sleep(2000); } } private void qiantai() { ThreadStart ts = new ThreadStart(DoWork); Thread thread = new Thread(ts); thread.IsBackground = false; //是前台线程 thread.Start(); } private void houtai() { ThreadStart ts = new ThreadStart(DoWork); Thread thread = new Thread(ts); thread.IsBackground = true; //后台线程 thread.Start(); } private void button1_Click(object sender, EventArgs e) { qiantai(); //总结: //默认情况下,新建的线程为前台线程; 可以通过isbackground来查看; //当所有的前台线程执行完毕之后,应用程序结束,不管后台进程是否执行完毕; //并释放掉全部资源; } } }
兄弟,自己去感受一下吧!