• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
统哥
博客园    首页    新随笔    联系   管理    订阅  订阅

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

 

posted @ 2020-08-28 09:54  统哥  阅读(2903)  评论(1)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3