对C#中Thread.IsBackground属性的理解

原文地址:

C#中,Thread类有一个IsBackground 的属性.MSDN上对它的解释是:获取或设置一个值,,该值指示某个线程是否为后台线程。个人感觉这样的解释等于没有解释.

.Net中的线程,可以分为后台线程和前台线程。后台线程与前台线程并没有本质的区别,它们之间唯一的区别就是:后台线程不会防止应用程序的进程被终止掉。呵呵,这句话读出来好像并不那么好懂.其实,说白了就是当前台线程都结束了的时候,整个程序也就结束了,即使还有后台线程正在运行,此时,所有剩余的后台线程都会被停止且不会完成.但是,只要还有一个前台线程没有结束,那么它将阻止程序结束.这就是为什么有些设计不够完美的WinForm程序,在某种特定的情况下,即使所有的窗口都关闭了,但是在任务管理器的管理列表里仍然可以找到该程序的进程,仍然在消耗着CPU和内存资源.因此,在WinForm程序中,关闭所有窗口前,应该停止所有前台线程,千万不要遗忘了某个前台线程.应用程序进程的存亡由前台线程决定而于后台线程无关.这就是它们的区别.

知道了前后台线程的区别,就应该知道如何声明IsBackgroud属性的值了.

值得说明的一点是:改变线程从前台到后台不会以任何方式改变它在CPU协调程序中的优先级和状态。因为前台后线程与程序进程的优先级无关.

结束前摘录MSDN上一段示例码,以帮助大家便好的理解这一区别:

下面的代码示例对比了前台线程与后台线程的行为。创建一个前台线程和一个后台线程。前台线程使进程保持运行,直到它完成它的while循环。前台线程完成后,进程在后台线程完成它的while循环之前终止。

using System;using System.Threading;class Test{static void Main(){BackgroundTest shortTest = new BackgroundTest(10);Thread foregroundThread =new Thread(new ThreadStart(shortTest.RunLoop));foregroundThread.Name = "ForegroundThread";BackgroundTest longTest = new BackgroundTest(50);Thread backgroundThread =new Thread(new ThreadStart(longTest.RunLoop));backgroundThread.Name = "BackgroundThread";backgroundThread.IsBackground = true;foregroundThread.Start();backgroundThread.Start();}}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属性的理解

相关文章:

你感兴趣的文章:

标签云: