CLR via C# 讀書筆記 1-3 前臺線程和后臺線程
前臺線程(Foreground)
后臺線程(Background)
相互作用:
當所有前臺線程退出的時候, CLR會強制終止所有的后臺線程,并且不會有異常拋出
請參考以下代碼(摘自CLR via C# ):
代碼
using System;
using System.Threading;
public static class Program
{
public static void Main()
{
// Create a new thread (defaults to foreground)
Thread t = new Thread(Worker);
// Make the thread a background thread
t.IsBackground = false;
t.Start(); // Start the thread
// If t is a foreground thread, the application won't die for about 10 seconds
// If t is a background thread, the application dies immediately
Console.WriteLine("Returning from Main");
}
private static void Worker()
{
Thread.Sleep(10000); // Simulate doing 10 seconds of work
// The line below only gets displayed if this code is executed by a foreground thread
Console.WriteLine("Returning from Worker");
}
}
轉換
你可以在任何時候轉換前臺線程為后臺線程,或者反過來. 只要線程還活著
默認值:
主線程默認是前臺線程
線程池默認是后臺線程
新建的默認是后臺線程
何時使用?
非關鍵性事務或者可恢復性質的事務,可以使用后臺線程
PS1:實際上用前臺線程的情況并不多,因為實際上還要考慮用戶直接干掉整個進程的情況
PS2:在服務器壓力很大或者服務器有某種不可預知缺陷的情況下,后臺線程出問題的幾率會比前臺線程大(例如莫名其妙不運行啦 什么的) , 這條只是個人意見 沒有經過非常嚴格的檢驗

浙公網安備 33010602011771號