Due to the time slice, although all threads are executed in a serial manner at the micro level, they can be considered as parallel execution at the macro level.
There are two types of threads: foreground and background. We can use the thread attribute isbackground = false to specify the frontend and backend attributes of the thread (the default is the foreground thread ).
The difference is that the program of the foreground thread can exit only after all the foreground threads have finished running. The program of the background thread, as long as the foreground thread is terminated, then the background thread will automatically end and launch the program.
Usage direction: Generally, foreground threads are used for long-waiting tasks, such as listening to client requests. Background threads are generally used to process short-time tasks, such as processing client-sent request information.
Foreground thread]
using System;using System.Collections.Generic;using System.Text;using System.Threading;namespace Demo{ class Program { static void Main(string[] args) { Thread aThread = new Thread(threadFunction); Console.WriteLine("Thread is starting..."); aThread.Start(); Console.WriteLine("Application is terminating..."); } public static void threadFunction() { Console.WriteLine("Thread is sleeping..."); Thread.Sleep(5000); Console.WriteLine("Thread is aborted!"); } }}
Background thread]
using System;using System.Collections.Generic;using System.Text;using System.Threading;namespace Demo{ class Program { static void Main(string[] args) { Thread aThread = new Thread(threadFunction); aThread.IsBackground = true; Console.WriteLine("Thread is starting..."); aThread.Start(); Console.WriteLine("Application is terminating..."); } public static void threadFunction() { Console.WriteLine("Thread is sleeping..."); Thread.Sleep(5000); Console.WriteLine("Thread is aborted!"); } }}