首页 新闻 会员 周边 捐助

C#线程问题

0
[已关闭问题] 关闭于 2018-10-10 18:16

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;

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

    class ThreadSample
    {
        private readonly int _iterations;

        public ThreadSample(int iterations)
        {
            _iterations = iterations;
        }
        public void CountNumbers()
        {
            for (int i = 0; i < _iterations; i++)
            {
                Thread.Sleep(TimeSpan.FromSeconds(0.5));
                Console.WriteLine("{0} prints {1}", Thread.CurrentThread.Name, i);
            }
        }
    }

上面这段代码中,设定了threadTwo为后台线程,线程threadOne作为前台线程完成后程序应该结束并且后台线程被终结,结果应该是ThreadOne执行完程序结束,但是我在最后加了一句Console.ReadKey()之后,ThreadTwo会在ThreadOne完成之后继续执行到结束,请问是因为Console.ReadKey()是在前台线程中并没有被完成,所以让线程二继续运行下去吗?

C#
Sheepishly的主页 Sheepishly | 菜鸟二级 | 园豆:204
提问于:2018-10-10 17:30
< >
分享
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册