進程會等待所有的前臺線程完成後在結束工作,但是如果只剩下後臺線程,則會直接結束工作 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading ...
進程會等待所有的前臺線程完成後在結束工作,但是如果只剩下後臺線程,則會直接結束工作
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Threading; using System.Diagnostics; namespace testThread { class Program { static void Main(string[] args) { var sampleForegroud = new ThreadSample(10); var sampleBackgroud = new ThreadSample(20); var threadone = new Thread(sampleForegroud.CountNumbers); threadone.Name = "ForegroudThread"; var threadtwo = new Thread(sampleBackgroud.CountNumbers); threadtwo.Name = "BackgroudThread"; threadtwo.IsBackground = true; 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(TimeSpan.FromSeconds(0.5)); Console.WriteLine("{0} Print {1}", Thread.CurrentThread.Name, i); } } } }View Code