1. 程式人生 > >C# 前臺執行緒與後臺執行緒

C# 前臺執行緒與後臺執行緒

由於時間片的原因,雖然所有執行緒在微觀上是序列執行的,但在巨集觀上可以認為是並行執行。

執行緒有兩種型別:前臺和後臺。我們可以通過執行緒屬性IsBackground=false來指定執行緒的前後臺屬性(預設是前臺執行緒)。

區別是:前臺執行緒的程式,必須等所有的前臺執行緒執行完畢後才能退出;而後臺執行緒的程式,只要前臺的執行緒都終止了,那麼後臺的執行緒就會自動結束並推出程式。

用法方向:一般前臺執行緒用於需要長時間等待的任務,比如監聽客戶端的請求;後臺執行緒一般用於處理時間較短的任務,比如處理客戶端發過來的請求資訊。

【前臺執行緒】

[csharp]
  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Threading;  
  5.   
  6. namespace Demo  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             Thread aThread = new
     Thread(threadFunction);  
  13.             Console.WriteLine("Thread is starting...");  
  14.             aThread.Start();  
  15.             Console.WriteLine("Application is terminating...");  
  16.         }  
  17.   
  18.         public static void threadFunction()  
  19.         {  
  20.             Console.WriteLine("Thread is sleeping...");  
  21.             Thread.Sleep(5000);  
  22.             Console.WriteLine("Thread is aborted!");  
  23.         }  
  24.     }  
  25. }  


【後臺執行緒】 

[csharp]  view plain  copy
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Text;  
  4. using System.Threading;  
  5.   
  6. namespace Demo  
  7. {  
  8.     class Program  
  9.     {  
  10.         static void Main(string[] args)  
  11.         {  
  12.             Thread aThread = new Thread(threadFunction);  
  13.             aThread.IsBackground = true;  
  14.             Console.WriteLine("Thread is starting...");  
  15.             aThread.Start();  
  16.             Console.WriteLine("Application is terminating...");  
  17.         }  
  18.   
  19.         public static void threadFunction()  
  20.         {  
  21.             Console.WriteLine("Thread is sleeping...");  
  22.             Thread.Sleep(5000);  
  23.             Console.WriteLine("Thread is aborted!");  
  24.         }  
  25.     }