前台和后台线程Foreground and Background Threads

托管线程可以是后台线程,也可以是前台线程。A managed thread is either a background thread or a foreground thread. 后台线程和前台线程几乎完全相同,只有一处不同,即后台线程不会确保托管执行环境一直运行。Background threads are identical to foreground threads with one exception: a background thread does not keep the managed execution environment running. 一旦托管进程(其中 .exe 文件为托管程序集)中的所有前台线程都停止,系统会停止并关闭所有后台线程。Once all foreground threads have been stopped in a managed process (where the .exe file is a managed assembly), the system stops all background threads and shuts down.

备注

如果运行时因进程正在关闭而停止后台线程,不会在线程中抛出任何异常。When the runtime stops a background thread because the process is shutting down, no exception is thrown in the thread. 不过,如果线程因 AppDomain.Unload 方法卸载应用域而停止,前台线程和后台线程中都会抛出 ThreadAbortExceptionHowever, when threads are stopped because the AppDomain.Unload method unloads the application domain, a ThreadAbortException is thrown in both foreground and background threads.

Thread.IsBackground 属性可用于确定是后台线程还是前台进程,也可用于更改线程状态。Use the Thread.IsBackground property to determine whether a thread is a background or a foreground thread, or to change its status. 可以随时将线程的 IsBackground 属性更改为 true,将线程更改为后台线程。A thread can be changed to a background thread at any time by setting its IsBackground property to true.

重要

线程的前台或后台状态不会影响线程中抛出未经处理的异常。The foreground or background status of a thread does not affect the outcome of an unhandled exception in the thread. 在 .NET Framework 版本 2.0 中,前台线程或后台线程中未经处理的异常会导致应用终止。In the .NET Framework version 2.0, an unhandled exception in either foreground or background threads results in termination of the application. 请参阅托管线程异常See Exceptions in Managed Threads.

属于托管线程池的线程(即 IsThreadPoolThread 属性为 true 的线程)是后台线程。Threads that belong to the managed thread pool (that is, threads whose IsThreadPoolThread property is true) are background threads. 从非托管代码进入托管执行环境的所有线程都会标记为后台线程。All threads that enter the managed execution environment from unmanaged code are marked as background threads. 默认情况下,通过新建并启动 Thread 对象生成的所有线程都是前台线程。All threads generated by creating and starting a new Thread object are by default foreground threads.

如果使用线程监视活动(如套接字连接),请将它的 IsBackground 属性设置为 true,以便线程不会阻止进程终止。If you use a thread to monitor an activity, such as a socket connection, set its IsBackground property to true so that the thread does not prevent your process from terminating.

请参阅See also