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); } }