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); } }
C# Thread IsBackground 前后台线程巴克莱银行、 金牌讲师、 2017从"新"启航 Newegg助你快速掘金、 细数这两年亚马逊品牌备案的优势、 爆款打造方法、 备战12.12大促,Shopee Listing这样优化!、 厦门有几个美食街?好玩吗?、 厦门观音山有哪些好玩的?、 买桂林特产去哪里买比较好?、
没有评论:
发表评论