C# 线程介绍
一、前台线程与后台线程
1)一个进程可以有至少一个前台线程和任意个后台线程。只要有1个前台线程在运行,应用程序的进程都在运行。 当所有前台程序都结束,进程也就结束。CLR会终止该进程下的所有后台线程,可能导致该后台线程中的比如finally都来不及执行。
2)默认情况下,用Thread创建的前台进程都是前台线程,
3)可用isBackground= true.可以设置为后台
下例中,因为Main函数启动线程后就结束了。如果线程是前台线程那么会等待其执行完毕;如果线程是后台线程,会在main函数结束后立即结束。
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);
}
}
class Program
{
static void Main(string[] args)
{
//bool bTestBackground = false; //测试前台程序
bool bTestBackground = true; //测试后台程序
if (bTestBackground==false)
{
Console.WriteLine("测试前台程序" );
BackgroundTest TestObject = new BackgroundTest(20);
Thread foregroundThread =
new Thread(new ThreadStart(TestObject.RunLoop));
foregroundThread.Name = "ForegroundThread";
foregroundThread.Start();
}
else
{
Console.WriteLine("测试后台程序");
BackgroundTest TestObject = new BackgroundTest(20);
Thread backgroundThread =
new Thread(new ThreadStart(TestObject.RunLoop));
backgroundThread.Name = "BackgroundThread";
backgroundThread.IsBackground = true; //以下这行注释与否,可以区别前台以及后台程序
backgroundThread.Start();
}
}
}