1.這是一個 后台線程,IsBackground=true, 主線程完成后,后台子線程也停止了,即使 子線程 還有沒運行完,也要停止
class Program { static void Main(string[] args) { Thread t = new Thread(() => { Console.WriteLine("5秒后,運行子線程"); Thread.Sleep(TimeSpan.FromSeconds(5)); Console.WriteLine("運行完畢"); Console.WriteLine("5秒后,再運行子線程任務"); Thread.Sleep(TimeSpan.FromSeconds(5)); Console.WriteLine("因為主線程要求6秒完成, 這里需要10秒,所以這句話不會輸出"); Console.ReadKey(); }); t.IsBackground = true;//設置為后台線程,主線程完成后,后台線程也停止 t.Start(); Console.WriteLine("主線程給 后台子線程 6秒完成任務"); Thread.Sleep(TimeSpan.FromSeconds(6)); Console.WriteLine("主線程完成了"); } }
2.因為線程IsBackground=false,不是后台線程,所以主線程即使完成了,子線程也會繼續完成
class Program { static void Main(string[] args) { Thread t = new Thread(() => { Console.WriteLine("5秒后,運行子線程"); Thread.Sleep(TimeSpan.FromSeconds(5)); Console.WriteLine("子線程運行完畢"); Console.WriteLine("5秒后,再運行子線程任務"); Thread.Sleep(TimeSpan.FromSeconds(5)); Console.WriteLine("因為線程IsBackground = false,不是后台線程,所以主線程即使完成了,子線程也會繼續完成"); Console.WriteLine("請按任意鍵結束。。。。"); Console.ReadKey(); }); t.IsBackground = false;//因為線程IsBackground = false,不是后台線程,所以主線程即使完成了,子線程也會繼續完成 t.Start(); Console.WriteLine("主線程給 子線程 6秒完成任務"); Thread.Sleep(TimeSpan.FromSeconds(6)); Console.WriteLine("主線程完成了"); } }