class Program
{
static void Main(string[] args)
{
TestBackGround tbg=new TestBackGround(10);
Thread th = new Thread(new ThreadStart(tbg.reCount));
TestBackGround rtbg = new TestBackGround(5); // 如果此处的5为50
Thread rth = new Thread(new ThreadStart(rtbg.reCount));
rth.IsBackground = true;
rth.Start();
th.Start();
}
}
class TestBackGround
{
int count;
public TestBackGround(int _count)
{
this.count = _count;
}
public void reCount()
{
string threadName=Thread.CurrentThread.Name;
for (int i = 0; i < count; i++)
{
Console.WriteLine( i.ToString());
Thread.Sleep(1000);
}
Console.WriteLine("Finish Counting " + threadName);
}
}
///////////////////////////////////
例子 输出:
当标示处为5时,程序会一直运行下去。即使后台的程序运行结束,前台仍然会继续运行下去,然后Application关闭
。。。。。50时,程序会在前台程序结束后 , 关闭这个Application, 但是后台程序并未完成运行。
本文通过一个C#示例程序展示了前台线程与后台线程的区别。当后台线程标记为IsBackground=true时,若主程序结束,后台线程将被强制停止。文中对比了不同参数设置下程序的行为差异。
2254

被折叠的 条评论
为什么被折叠?



