The common language runtime (Common Language runtime,clr) of net can differentiate between two different types of threads: foreground and background threads. The difference between the two is that the application must run out of all foreground threads to exit, and for a background thread, the application can exit without considering whether it has finished running, and all background threads will automatically end when the application exits.
Whether a thread is a foreground thread or a background thread can be determined by its IsBackground property. This property is readable and writable. Its default value is False, which means that a line Cheng is considered a foreground thread. We can set its IsBackground property to true so that it becomes a background thread.
The following example is a console program in which the program starts with 10 threads and each thread runs for 5 seconds. Because the thread's IsBackground property defaults to False, which means that they are all foreground threads, the program's main thread runs out very quickly, but it will not end until all the threads that have started are finished running. The sample code is as follows:
Using System;
Using System.Threading;
Class MYAPP
{
public static void Main ()
{
for (int i = 0; i <; i++)
{
Thread thread = new Thread (new ThreadStart (ThreadFunc));
Thread. Start ();
}
}
private static void ThreadFunc ()
{
DateTime start = DateTime.Now;
while ((Datetime.now-start). Seconds < 5)
;
}
}
Next we make a slight modification to the above code to set the IsBackground property of each thread to true, and each thread is a background thread. So long as the main thread of the program is finished, the entire program is finished. The sample code is as follows:
Using System;
Using System.Threading;
Class MYAPP
{
public static void Main ()
{
for (int i = 0; i <; i++)
{
Thread thread = new Thread (new ThreadStart (ThreadFunc));
Thread. IsBackground = true;
Thread. Start ();
}
}
private static void ThreadFunc ()
{
DateTime start = datetime.now;
while (Datetime.now-start). Seconds < 5)
;
}
Since the foreground and background threads have this difference, how do we know how to set the IsBackground property of a thread? Here are some basic principles: for some threads running in the background, these threads should be set as background threads when the program ends without the need to continue running. For example, a program initiates a large number of operations of a thread, but as soon as the program is finished, the thread loses the meaning of the continuation, then the thread should be a background thread. Some threads that serve the user interface are often set up as foreground threads, because even if the program's main thread ends, other UI threads are likely to continue to exist to display the relevant information, so they cannot be terminated immediately. Here I just give some principles, specific to the actual use of the programmer will often require further careful consideration.