Thread 區別前后台線程屬性IsBackground
1、 創建一個線程默認是前台線程,即IsBackground=true
2、 主線程的結束會關聯前台線程,前台線程會阻止主進程的結束,需等待前台線程完成。
3、 主進程結束時后台線程也會結束,即使沒有執行完成也會被中斷。
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); } }