C# 前臺執行緒與後臺執行緒
阿新 • • 發佈:2018-11-10
由於時間片的原因,雖然所有執行緒在微觀上是序列執行的,但在巨集觀上可以認為是並行執行。
執行緒有兩種型別:前臺和後臺。我們可以通過執行緒屬性IsBackground=false來指定執行緒的前後臺屬性(預設是前臺執行緒)。
區別是:前臺執行緒的程式,必須等所有的前臺執行緒執行完畢後才能退出;而後臺執行緒的程式,只要前臺的執行緒都終止了,那麼後臺的執行緒就會自動結束並推出程式。
用法方向:一般前臺執行緒用於需要長時間等待的任務,比如監聽客戶端的請求;後臺執行緒一般用於處理時間較短的任務,比如處理客戶端發過來的請求資訊。
【前臺執行緒】
[csharp]- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading;
- namespace Demo
- {
- class Program
- {
- static void Main(string[] args)
- {
- Thread aThread = new
- Console.WriteLine("Thread is starting...");
- aThread.Start();
- Console.WriteLine("Application is terminating...");
- }
- public static void threadFunction()
- {
- Console.WriteLine("Thread is sleeping...");
- Thread.Sleep(5000);
- Console.WriteLine("Thread is aborted!");
- }
- }
- }
【後臺執行緒】
- using System;
- using System.Collections.Generic;
- using System.Text;
- using System.Threading;
- namespace Demo
- {
- class Program
- {
- static void Main(string[] args)
- {
- Thread aThread = new Thread(threadFunction);
- aThread.IsBackground = true;
- Console.WriteLine("Thread is starting...");
- aThread.Start();
- Console.WriteLine("Application is terminating...");
- }
- public static void threadFunction()
- {
- Console.WriteLine("Thread is sleeping...");
- Thread.Sleep(5000);
- Console.WriteLine("Thread is aborted!");
- }
- }
- }