C#多線程之Thread類詳解
使用System.Threading.Thread類可以創(chuàng)建和控制線程。
常用的構(gòu)造函數(shù)有:
// 摘要: // 初始化 System.Threading.Thread 類的新實(shí)例,指定允許對(duì)象在線程啟動(dòng)時(shí)傳遞給線程的委托。 // // 參數(shù): // start: // System.Threading.ParameterizedThreadStart 委托,它表示此線程開始執(zhí)行時(shí)要調(diào)用的方法。 // // 異常: // System.ArgumentNullException: // start 為 null。 [SecuritySafeCritical] public Thread(ParameterizedThreadStart start); // // 摘要: // 初始化 System.Threading.Thread 類的新實(shí)例。 // // 參數(shù): // start: // System.Threading.ThreadStart 委托,它表示此線程開始執(zhí)行時(shí)要調(diào)用的方法。 // // 異常: // System.ArgumentNullException: // start 參數(shù)為 null。 [SecuritySafeCritical] public Thread(ThreadStart start);
1. 無參數(shù)創(chuàng)建線程
ThreadStart委托定義了一個(gè)返回類型位void的無參數(shù)方法。
public void Main()
{
Thread vThread = new Thread(ThreadFun);
//vThread.Name = "td_Name"; // 線程名稱
vThread.Start(); //開始執(zhí)行線程
Console.WriteLine("This is the main thread:id=" + Thread.CurrentThread.ManagedThreadId);
}
void ThreadFun() // 來自委托:ThreadStart
{
Console.WriteLine("Running in a new thread:id=" + Thread.CurrentThread.ManagedThreadId);
for (int i = 0; i < 10; i++)
{
Console.Write(".");
Thread.Sleep(500);
}
Console.WriteLine("THREAD END");
}
輸出結(jié)果:

將上訴代碼中的 ThreadFun() 用Lambda表達(dá)式替換,變成Thread的簡(jiǎn)便使用方式:
public void Main()
{
Thread vThread = new Thread(() =>
{
Console.WriteLine("Running in a new thread");
});
//vThread.Name = "td_Name"; // 線程名稱
vThread.Start(); //開始執(zhí)行線程
Console.WriteLine("This is the main thread");
}
2.給線程傳遞參數(shù)
兩種方式:一種是使用帶ParameterizedThreadStart委托的方法參數(shù)構(gòu)造Thread;另一種是創(chuàng)建一個(gè)自定義類,把線程的方法定義為實(shí)例方法,這樣先初始化實(shí)例的數(shù)據(jù),在啟動(dòng)線程。
如:傳遞參數(shù)
public struct TdData // 傳遞數(shù)據(jù)
{
public string Message; //數(shù)據(jù)string字段
}
使用第一種方式:
public void Main()
{
TdData tData = new TdData() { Message = "Thread Info" };
Thread vThread = new Thread(ThreadFun);
vThread.Start(tData); // 開始執(zhí)行線程,傳遞參數(shù)
Console.WriteLine("This is the main thread");
}
void ThreadFun(object pObj) // 來自委托:ParameterizedThreadStart
{
TdData vData = (TdData)pObj;
Console.WriteLine("In a new thread, Received:{0}", vData.Message);
}
使用第二種方式:先自定義一個(gè)類。
public class TdHelper
{
public TdData mData; // 傳遞數(shù)據(jù)
// 構(gòu)造函數(shù)
public TdHelper(TdData pData)
{
this.mData = pData;
}
public void ThreadFun() // 來自委托:ThreadStart
{
Console.WriteLine("In a new thread, TdDataMessage:{0}", mData.Message);
}
}
然后,在主線程(需要的地方)創(chuàng)建Thread并將實(shí)例方法TdHelper.ThreadFun()作為構(gòu)造函數(shù)的參數(shù)。
public void Main()
{
TdData tData = new TdData() { Message = "Thread Info" };
TdHelper tHelper = new TdHelper(tData); // 傳遞參數(shù)
Thread vThread = new Thread(tHelper.ThreadFun);
vThread.Start();
Console.WriteLine("This is the main thread");
}
3.后臺(tái)線程
默認(rèn)情況下,Thread類創(chuàng)建的線程事前臺(tái)線程,線程池中的線程總是后臺(tái)線程。只要有一個(gè)前臺(tái)線程在運(yùn)行,應(yīng)用程序的進(jìn)程就在運(yùn)行,如果多個(gè)前臺(tái)線程在運(yùn)行,而Main()方法結(jié)束了,應(yīng)用程序仍然事激活的,直到所有前臺(tái)線程完成任務(wù)。
可以通過設(shè)置Thread類實(shí)例的IsBackground屬性,來讓其成為后臺(tái)線程;
public void Main()
{
Thread vThread = new Thread(() =>
{
Console.WriteLine("New thread started"); // Title3
Thread.Sleep(5000);
Console.WriteLine("New thread completed"); // Title2
});
//vThread.IsBackground = true;
vThread.Start();
Console.WriteLine("This is the main thread"); // Title1
}
當(dāng)IsBackground屬性默認(rèn)為false時(shí),可以在控制臺(tái)完整地看到 3 句輸出信息;但如果將其設(shè)為true時(shí),則不等到第3條信息(Title2)輸出時(shí),主線程Main()已經(jīng)執(zhí)行完成,控制臺(tái)窗口就自動(dòng)關(guān)閉了。
4.線程的優(yōu)先級(jí)
通過Priority屬性,可以調(diào)整Thread類實(shí)例的優(yōu)先級(jí),默認(rèn)為: vThread.Priority = ThreadPriority.Normal; // 枚舉值
關(guān)系:Highest > AboveNormal > Normal > BelowNormal > Lowest
5.控制線程
調(diào)用Thread對(duì)象的Start()方法,可以創(chuàng)建線程。但是,在調(diào)用Start()方法后,新線程仍不是處于 Running 狀態(tài),而是 Unstarted 狀態(tài)。只有操作系統(tǒng)的線程調(diào)度器選擇了要運(yùn)行該線程,線程就會(huì)改為 Running 狀態(tài)。通過 Thread.ThreadState 屬性,可以獲得該線程當(dāng)前的狀態(tài)。
使用Thread.Sleep()方法,會(huì)使線程處于WaitSleepJoin狀態(tài),在經(jīng)歷Sleep()方法定義的時(shí)間段后,線程就會(huì)等待再次被操作系統(tǒng)調(diào)度。
要停止一個(gè)線程,可以調(diào)用 Thread.Abort() 方法。調(diào)用這個(gè)方法,會(huì)在接到終止命令的線程中拋出一個(gè) ThreadAbortException,用一個(gè)處理程序捕獲這個(gè)異常,線程可以在結(jié)束前完成一些清理工作。線程還可以在接收到調(diào)用 Thread.Abort() 方法的結(jié)果 ThreadAbortException 異常后繼續(xù)工作。如果線程沒有重置終止,接收到終止請(qǐng)求的線程的狀態(tài)就從 AbortRequested 改為 Aborted 。
如果要等待線程結(jié)束,就可以調(diào)用 Thread.Join() 方法,它會(huì)停止當(dāng)前線程,并把它設(shè)置為 WaitSleepJoin 狀態(tài),直到加入的線程完成為止。
參見: C#多線程之線程控制詳解
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
.NET使用IResourceMonitor實(shí)現(xiàn)獲取資源信息
在 Microsoft.Extensions.Diagnostics.ResourceMonitoring 包提供了一系列定制 API,專用于監(jiān)視 .NET 應(yīng)用程序的資源利用率,本文將利用IResourceMonitor來實(shí)現(xiàn)獲取資源狀態(tài)信息,感興趣的可以了解下2024-01-01
Unity?UGUI的EventSystem事件系統(tǒng)組件介紹使用
這篇文章主要為大家介紹了Unity?UGUI的EventSystem事件系統(tǒng)組件介紹使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-07-07
C#中List集合使用Max()方法查找到最大值的實(shí)例
這篇文章主要介紹了C#中List集合使用Max()方法查找到最大值的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2020-12-12
C#實(shí)現(xiàn)判斷操作系統(tǒng)是否為Win8以上版本
這篇文章主要介紹了C#實(shí)現(xiàn)判斷操作系統(tǒng)是否為Win8以上版本,本文講解了利用C#獲取OS的版本號(hào)、利用反射獲取當(dāng)前正在運(yùn)行的程序的版本信息、 利用C#判斷當(dāng)前操作系統(tǒng)是否為Win8系統(tǒng)等內(nèi)容,需要的朋友可以參考下2015-06-06
使用HttpHanlder處理404:File not found的問題
本篇文章小編為大家介紹。使用HttpHanlder處理404:File not found的問題。需要的朋友參考下2013-04-04

