C# 前台线程与后台线程的区别

    class Program
    {
        static void Main(string[] args)
        {
            var sampleForeground = new ThreadSample(10);
            var sampleBackground = new ThreadSample(20);

            var threadOne = new Thread(sampleForeground.CountNumbers);
            threadOne.Name = "ForegroundThread";
            var threadTwo = new Thread(sampleBackground.CountNumbers);
            threadTwo.Name = "BackgroundThread";

            threadTwo.IsBackground = true;  //如果讲这行代码注释,那程序就会输出20次

            threadOne.Start();
            threadTwo.Start();
        }
    }

    class ThreadSample
    {
        private readonly int _iterations;

        public ThreadSample(int iterations)
        {
            _iterations = iterations;
        }

        public void CountNumbers()
        {
            for(int i = 0; i < _iterations; i++)
            {
                Thread.Sleep(500);
                Console.WriteLine("{0}输出:{1}",Thread.CurrentThread.Name,i);
            }
        }
    }

这里定义了一个前台线程和后台线程,执行这段代码,程序将输出10次。

如果将第二个线程也改成前台线程,那么程序将输出20次。

 

所以前台线程和后台线程的区别就是,当前台线程完成后,后台线程哪怕还没有完成也会被终结。

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值