GOTCHA #49 Foreground threads may prevent a program from terminatingThe IsBackground property on a THRead indicates whether the thread is a background (daemon) thread. The CLR quits executing if only background threads are running. In other words, in normal execution the CLR does not terminate as long as there is at least one non-background thread running. In your application, if you start a thread and leave it running in the foreground (which is the default), then exit the program (by leaving Main() or by clicking on the close box in a Windows application), the program continues to run as long as that thread runs. But if you set the thread to background, the program will terminate when you expect it to. Consider Example 7-1. Example 7-1. Thread behavior
//Test.cs using System; using System.Threading; namespace Background { class Test { private static void Worker() { // Some activity Thread.Sleep(5000); Console.WriteLine("worker done at {0}", DateTime.Now.ToLongTimeString()); } [STAThread] static void Main(string[] args) { Thread workerThread = new Thread(new ThreadStart(Worker)); //workerThread.IsBackground = true; workerThread.Start(); Console.WriteLine("Main done at {0}", DateTime.Now.ToLongTimeString()); } } }
Imports System.Threading Module Test Private Sub Worker() 'Some activity Thread.Sleep(5000) Console.WriteLine("worker done at {0}", _ DateTime.Now.ToLongTimeString()) End Sub Sub Main() Dim workerThread As New Thread(AddressOf Worker) 'workerThread.IsBackground = true workerThread.Start() Console.WriteLine("Main done at {0}", _ DateTime.Now.ToLongTimeString()) End Sub End Module In this example you create a THRead instance, assign it to execute the Worker() method, and start it. You print the message that Main() is done and leave the Main() method. When executed, the program will continue to run even after Main() completes. It terminates only after the Worker() method in the second thread completes, as shown in Figure 7-1. Figure 7-1. Output from Example 7-1![]() If you uncomment the statement workerThread.IsBackground = true, the program terminates when it leaves the Main() method, as shown in Figure 7-2. Figure 7-2. Output from Example 7-1 with IsBackground = true![]() By default, threads are created in the foreground. Should you set IsBackground to true or not? Say you are performing a search in another thread. If the user quits the application, you may want the program to terminate. In this case, you need to set the thread to a background thread. On the other hand, if the task the other thread is performing is critical, and should be carried out no matter what other threads are running, then you don't want to set it as background. |