Background and foreground threads, background foreground threads
From MSDN
A hosted thread, a background thread, or a foreground thread. The background thread does not make the Managed execution environment running. In addition, the background thread is the same as the foreground thread. Once all foreground threads are stopped in a hosted process (where the. exe file is a hosted assembly), the system stops all background threads and closes them.
Note: |
When the running database stops a background thread because the process is disabled, no exception is thrown in this thread. However, when the thread is stopped because the System. AppDomain. Unload (System. AppDomain) method unmounts the application domain, ThreadAbortException is triggered in both the background and foreground threads. |
Use the Thread. IsBackground attribute to determine whether the Thread is a background Thread or a foreground Thread, or change its status. By setting its IsBackground attribute to true, you can change the thread to a background thread at any time.
Key Points |
The frontend or backend status of the thread does not affect the result of unhandled exceptions in the thread. In. NET Framework 2.0, unprocessed exceptions in the foreground or background threads will cause the application to terminate. See exceptions in managed threads. |
The thread that belongs to the managed thread pool (that is, the thread whose IsThreadPoolThread attribute is true) is the background thread. All threads that enter the Managed execution environment from unmanaged code are marked as background threads. All threads generated by creating and starting a new Thread object are foreground threads by default.
If you use a thread to monitor activity (such as socket connection), set its IsBackground attribute to true so that the thread does not stop the process from terminating.
This means that once the main thread of the program is closed (the program will be closed after the code execution body of the main thread is completed), the background thread will not be forcibly closed and will not cause exceptions. Therefore, if a background thread is running, ensure that the foreground thread is not closed.