今天在执行一段前后台线程的时候,发现了我把线程全部都设置成了后台线程IsBackground = true,但是还是会执行后台线程,一直执行完后台线程。
代码如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Linq.Expressions; usingSystem.Reflection; usingSystem.Threading; namespaceConsoleApp1 { classProgram { static void Main(string[] args) { //演示前台、后台线程 BackGroundTest background = new BackGroundTest(10); //创建前台线程,默认创建的都是前台线程 Thread fThread = new Thread(newThreadStart(background.RunLoop)); //给线程命名 fThread.Name = "前台线程"; BackGroundTest background1 = new BackGroundTest(20); //创建后台线程 Thread bThread = new Thread(newThreadStart(background1.RunLoop)); bThread.Name = "后台线程"; //设置为后台线程 bThread.IsBackground = true; //启动线程 fThread.Start(); bThread.Start(); Console.ReadLine(); } } }
usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Threading; namespaceConsoleApp1 { public classBackGroundTest { private intCount; public BackGroundTest(intcount) { this.Count =count; } public voidRunLoop() { //获取当前线程的名称 string threadName =Thread.CurrentThread.Name; for (int i = 0; i < Count; i++) { Console.WriteLine("{0}计数:{1}", threadName, i.ToString()); //线程休眠1000毫秒 Thread.Sleep(1000); } Console.WriteLine("{0}完成计数", threadName); } } }
运行结果:
想要得到的结果理论上应该是 后台线程也不会运行了。
想了想,问题就应该出在最后一行代码:
Console.ReadLine();,它会让结果窗口一直不关闭,一直运行,窗口不关闭,后台线程也会一直运行,就会不停的打印结果.
把代码修改下,去掉了 Console.ReadLine();
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Linq.Expressions; usingSystem.Reflection; usingSystem.Threading; namespaceConsoleApp1 { classProgram { static void Main(string[] args) { //演示前台、后台线程 BackGroundTest background = new BackGroundTest(10); //创建前台线程,默认创建的都是前台线程 Thread fThread = new Thread(newThreadStart(background.RunLoop)); //给线程命名 fThread.Name = "前台线程"; BackGroundTest background1 = new BackGroundTest(20); //创建后台线程 Thread bThread = new Thread(newThreadStart(background1.RunLoop)); bThread.Name = "后台线程"; //设置为后台线程 bThread.IsBackground = true; //启动线程 fThread.Start(); bThread.Start(); } } } usingSystem; usingSystem.Collections.Generic; usingSystem.Text; usingSystem.Threading; namespaceConsoleApp1 { public classBackGroundTest { private intCount; public BackGroundTest(intcount) { this.Count =count; } public voidRunLoop() { //获取当前线程的名称 string threadName =Thread.CurrentThread.Name; for (int i = 0; i < Count; i++) { Console.WriteLine("{0}计数:{1}", threadName, i.ToString()); //线程休眠1000毫秒 Thread.Sleep(1000); } Console.WriteLine("{0}完成计数", threadName); } } }
再看运行结果:
就达到了预期的效果,前台线程运行完毕,后台线程尽管没运行完,也关闭了。
以后再写代码中要注意:
Console.ReadLine(); //这句话很重要,如果不注释掉这段代码,即使设置了 bThread.IsBackground = true,也没效果,因为前台线程还没结束,一直在执行,就不会停掉后台线程,后台线程会一直执行到结束。
这是个小细节,稍不留神,就跳到坑里面了。