流星,霎那划过天际

导航

前台线程与后台线程

参考 MSDN http://msdn.microsoft.com/zh-cn/library/h339syd0.aspx

 

一旦所有前台线程在托管进程(其中 .exe 文件是托管程序集)中被停止,系统将停止所有后台线程并关闭。

 

案例1:

创建2个前台线程

案例1
        private static void Main()
        {    Thread thread0 
= new Thread(new ThreadStart(ThreadMethod0));
            Thread thread1 
= new Thread(new ThreadStart(ThreadMethod1));
            thread0.Name 
= "thread0";
            thread1.Name 
= "thread1";
            thread0.IsBackground 
= true;
            thread1.IsBackground 
= true;
            thread0.Start();
            thread1.Start();        
        }

        
private static void ThreadMethod0()
        {
            
for (int i = 0; i < 5; i++)
            {
                Debug.WriteLine(
"0");
                Thread.Sleep(
2000);
            }
        }

        
private static void ThreadMethod1()
        {
            
for (int i = 0; i < 5; i++)
            {
                Debug.WriteLine(
"1");
                Thread.Sleep(
2000);
            }
        }

 输出结果为:

0

1

0

1

0

1

0

1

0

1

 

案例2:

 创建2个后台线程,即保持原代码不变,将

            
thread0.IsBackground 
= false;
thread1.IsBackground 
= false;

 

 输出结果为:

 

案例3:

 创建1个前台线程,1个后台线程,即保持原代码不变,将

thread0.IsBackground = false;
thread1.IsBackground 
= true;

 

 输出结果为:

0

1

0

1

0

1

0

1

0

1

 

 

posted on 2010-03-01 11:32  流星,霎那划过天际  阅读(215)  评论(0编辑  收藏  举报