There are two types of threads: foreground thread, background thread. The foreground and background threads are the same nature, but the termination conditions are different.
Background thread: If the host process ends during the run, the thread terminates execution directly, and at force termination, the thread terminates execution regardless of whether the thread code is executed.
Foreground thread: If the host process ends during the run, the thread continues execution until the thread code executes, and at the forced termination, the thread ends regardless of whether or not the thread code is executed.
Background Thread life cycle:
Display: The background thread must end as long as the host process ends
Display: The background thread has finished executing or is forcibly terminated, and the host process is not finished
--------------------------------------------------------------------------------------------------------------- --
Foreground thread life cycle:
Display: The foreground thread has finished executing or is forcibly terminated, and the host process is not finished
Display: When the host process finishes executing, but the foreground thread function is not completed, the thread will no longer depend on the process to continue execution until the code finishes executing
private static void Multithreadlifecycle () {Parameterizedthreadstart task = (sleep) + = { int i = Convert.ToInt32 (sleep); try {for (var i = 0; i < i++) {Consol E.writeline (String.Format ("Thread {0} out:{1}", Thread.CurrentThread.Name, i)); Thread.Sleep (i); } Console.WriteLine (String.Format ("Sub Thread {0} The End", Thread.CurrentThread.Name)); } catch (ThreadAbortException ex) {Console.WriteLine (String.Format ("Su b Thread {0} Abort ", Thread.CurrentThread.Name)); } }; Console.WriteLine ("Main Thread"); Thread thread1 = new Thread (Task) {Name = "thread1"}; Thread thread2 = new Thread (Task) {Name = "tHread2 ", IsBackground = true}; Thread1. Start (5000); Thread2. Start (5000); Console.WriteLine ("Main thread Wait Sub Thread"); Thread1. Abort (); Console.ReadLine (); Console.WriteLine (String.Format ("{0}:{1},{2}:{3}", Thread1. Name, Thread1. ThreadState, Thread2. Name, Thread2. ThreadState)); }
Description
1, set whether the off-the-shelf is a background thread, can be set through the IsBackground property of thread object
2. The force-terminating thread can be done through the thread object's abort () method, and ThreadAbortException exception handling should be performed in threads because the exception is thrown when a thread that does not execute completes is forced to finish.
C # Multi-Threading Usage 2-Thread life cycle