GOTCHA #50 Background threads don't terminate gracefullyIn Gotcha #49, "Foreground threads may prevent a program from terminating," you saw the advantage of setting a thread as background. Such a thread runs only as long as a foreground thread is running. But if your background thread uses critical resources, you want to make sure that it terminates gracefully. The MSDN documentation says,
If you write a method that executes in the background, you should expect its thread to terminate when all foreground threads quit. Unfortunately, contrary to what Microsoft's documentation might lead you to expect, the termination is not graceful. Let's look at Example 7-2. Example 7-2. Abrupt termination of a background threadC# (BackgroundAbort) using System; using System.Threading; namespace BackgroundThreadAndAbort { class Test { private static void Worker() { Console.WriteLine( "Worker started... given chance to cleanup?"); try { Thread.Sleep(5000); } catch(ThreadAbortException) { Console.WriteLine( "Thread aborted exception received"); } } [STAThread] static void Main(string[] args) { Thread workerThread = new Thread(new ThreadStart(Worker)); workerThread.IsBackground = true; workerThread.Start(); Thread.Sleep(2000); Console.WriteLine("Main done"); } } } VB.NET (BackgroundAbort) Imports System.Threading Module Test Private Sub Worker() Console.WriteLine( _ "Worker started... given chance to cleanup?") Try Thread.Sleep(5000) Catch ex As ThreadAbortException Console.WriteLine("Thread aborted exception received") End Try End Sub Public Sub Main() Dim workerThread As New Thread(AddressOf Worker) workerThread.IsBackground = True workerThread.Start() Thread.Sleep(2000) Console.WriteLine("Main done") End Sub End Module In this program, you start a background thread that executes the Worker() method. In that method you anticipate the THReadAbortException. When Main() terminates, the background thread executing the Worker() method is terminated. However, the ThreadAbortException is not thrown on it. This is shown in the output in Figure 7-3. As a result, the background thread has no chance to clean up and exit gracefully. It just gets yanked. Figure 7-3. Output from Example 7-2IN A NUTSHELLRemember that background threads are killed abruptly when the process terminates and do not have an opportunity to clean up gracefully. SEE ALSOGotcha #49, "Foreground threads may prevent a program from terminating" and Gotcha #53, "Environment.Exit() brings down the CLR." |