C#/.NET主线程与子线程之间的关系

一般来说,一个应用程序就对应一个进程,一个进程可有一个或多个线程,只有一个主线程。

主线程与子线程之间的关系

  1. 默认情况,在新开启一个子线程的时候,他是前台线程,只有将线程的IsBackground属性设为true;他才是后台线程
  2. 当子线程是前台线程,则主线程结束并不影响其他线程的执行,只有所有前台线程都结束,程序结束
  3. 当子线程是后台线程,则主线程的结束,会导致子线程的强迫结束
  4. 不管是前台线程还是后台线程,如果线程内出现了异常,都会导致进程的终止。
  5. 托管线程池中的线程都是后台线程,使用new Thread方式创建的线程默认都是前台线程。

如此设计的原因:

因为后台线程一般做的都是需要花费大量时间的工作,如果不这样设计,主线程已经结束,而后台工作线程还在继续,第一有可能使程序陷入死循环,第二主线程已经结束,后台线程即时执行完成也没有实际的意义.

检测以上观点

  class Program
    {
        public static AutoResetEvent autoEvent = new AutoResetEvent(false);
        static void Main(string[] args)
        {
            Console.WriteLine("主线程开始");

            Thread.Sleep(1000);
            Console.WriteLine("主线程在做其他事");

            //ParameterizedThreadStart parameterizedThreadStart1 = new ParameterizedThreadStart(Test1);
            //Thread thread1 = new Thread(parameterizedThreadStart1) { IsBackground = false };
            //thread1.Name = "前台线程:";
            //thread1.Start(thread1);

            ParameterizedThreadStart parameterizedThreadStart2 = new ParameterizedThreadStart(Test1);
            Thread thread2 = new Thread(parameterizedThreadStart2) { IsBackground = true };
            thread2.Name = "后台线程:";
            thread2.Start(thread2);

            Console.WriteLine("主线程结束");
        }

        public static void Test1(object current)
        {
            Console.WriteLine(((Thread)current).Name+"线程开始");
            autoEvent.WaitOne();
            //((AutoResetEvent)current).Set();
        }
    }

效果图

后台线程

这里写图片描述

前台线程

这里写图片描述

猜你喜欢

转载自blog.csdn.net/qq_27445903/article/details/79225543