欢迎光临
我的个人博客网站

C# Thread IsBackground 前后台线程

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);             }         }

 

赞(0) 打赏
未经允许不得转载:张拓的天空 » C# Thread IsBackground 前后台线程
分享到: 更多 (0)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

专业的IT技术经验分享 更专业 更方便

联系我们本站主机

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏