When to Use Background Threads In general your application should have one main thread. The application's user interface should be driven by this thread, and when all the active windows are closed the application should terminate. Terminating the application usually requires telling any running background threads to shut down and then with no application windows open to keep the main thread alive its execution can end. (At this point, the main() function of the application is exited and control is handed back to the runtime and operating system to do any final cleanup.) Having multiple threads managing their own user interface windows greatly complicates this model and should be avoided.Occasionally some action a user requests will require a significant amount or indeterminate amount of time to complete. If the time required to complete a needed task is only a few seconds, you may choose to pop up a wait cursor and perform the operation synchronously on the user interface's thread. If the time required is longer or indeterminate in length, pushing the work onto a background thread is an appropriate solution. There are two ways to do this:Create a new thread. In this model, a new thread is started and a function is specified as its entry point. The function runs and when it exits the thread terminates.Have a background thread waiting for work. In this model, a background thread or pool of threads is created in advance and waits for work to perform. Typically the background threads sit sleeping either blocked and waiting for some action to wake them or periodically waking up based on a timer to look for work. A woken-up thread performs the requested work and then goes back to sleep to wait for additional requests to wake it again. |