Thread 區別先後臺線程屬性IsBackgroundoop
一、 建立一個線程默認是前臺線程,即IsBackground=truethis
二、 主線程的結束會關聯前臺線程,前臺線程會阻止主進程的結束,需等待前臺線程完成。spa
三、 主進程結束時後臺線程也會結束,即便沒有執行完成也會被中斷。線程
static void Main(string[] args) { BackgroundTest shortTest = new BackgroundTest(50); Thread foregroundThread = new Thread(new ThreadStart(shortTest.RunLoop)); foregroundThread.Name = "ForegroundThread"; BackgroundTest longTest = new BackgroundTest(100); Thread backgroundThread = new Thread(new ThreadStart(longTest.RunLoop)); backgroundThread.Name = "BackgroundThread"; backgroundThread.IsBackground = true; foregroundThread.Start(); backgroundThread.Start();
Task.Factory.StartNew(() => { Thread.CurrentThread.Name = "Task Thread"; Thread.CurrentThread.IsBackground = false; //設置爲前臺線程 new BackgroundTest(50).RunLoop(); });
//回車結束主線程,若是有前臺線程在運行是沒法結束的,(後臺線程就會被終止,不會執行完成) Console.ReadLine(); } class BackgroundTest { int maxIterations; public BackgroundTest(int maxIterations) { this.maxIterations = maxIterations; } public void RunLoop() { String threadName = Thread.CurrentThread.Name; for (int i = 0; i < maxIterations; i++) { Console.WriteLine("{0} count: {1}", threadName, i.ToString()); Thread.Sleep(250); } Console.WriteLine("{0} finished counting.", threadName); } }