.Net Framework提供了Thread類,它可以創建和控制線程。Thread的構造方法可接受一個無參無返回值的委托類型參數,或一個有object類型參數無返回值的委托類型參數。
1、簡單的Thread類實例
先創建兩個方法,分別用於兩個線程處理:
1: static void ThreadMethod1()
2: {
3: for (int j = 0; j < 20; j++)
4: {
5: Console.WriteLine("Thread 1 is running");
6: Thread.Sleep(500);
7: }
8: }
9:
10: static void ThreadMethod2()
11: {
12: for (int j = 0; j < 20; j++)
13: {
14: Console.WriteLine("Thread 2 is running");
15: Thread.Sleep(500);
16: }
17: }
兩個線程將都是循環20次,每隔500ms輸出字符串到控制台。然后在主線程里啟動這兩個線程:
1: static void Main(string[] args)
2: {
3: Thread thread1 = new Thread(ThreadMethod1);
4: Thread thread2 = new Thread(ThreadMethod2);
5:
6: thread1.Start();
7: thread2.Start();
8:
9: Console.Read();
10: }
可以看到結果是"Thread 1 is running"和"Thread 2 is running"出現,但可能不完全是交替出現,因為兩個線程是同時在走,某一個時間點上哪個線程到前台是由操作系統調度的。
2、線程數據傳遞
往線程里傳遞數據有兩種方式。
(1)ParameterizedThreadStart委托參數
如果使用ParameterizedThreadStart委托,線程的入口必須有一個object類型參數。這個參數在線程內可以強制轉換為任意數據類型。
先定義一個結構作為輸入參數的類型:
1: struct ThreadData
2: {
3: public string Message;
4: }
定義一個方法,在線程里調用:
1: static void ThreadMethod3(object param)
2: {
3: ThreadData data = (ThreadData)param;
4:
5: for (int i = 0; i < 20; i++)
6: {
7: Console.WriteLine(String.Format("Thread 3 is running. Message: {0}", data.Message));
8: }
9: }
方法里把輸入的參數強制轉成了ThreadData類型。
然后在主線程里啟動這個線程,用Start方法傳入數據:
1: Thread thread3 = new Thread(ThreadMethod3);
2: thread3.Start(new ThreadData() { Message = "Hello world!" });
從結果就可以看到“Hello World!”傳入了線程。
(2)實例方法
用上一個例子,定義一個類,其中包含一個數據字段和線程方法:
1: class Thread4Class
2: {
3: public string Message { get; set; }
4:
5: public void ThreadMethod4()
6: {
7: for (int i = 0; i < 20; i++)
8: {
9: Console.WriteLine(String.Format("Thread 4 is running. Message: {0}", Message));
10: Thread.Sleep(500);
11: }
12: }
13: }
然后在主線程里啟動:
1: Thread4Class thread4Class = new Thread4Class() { Message = "Hello world!" };
2: Thread thread4 = new Thread(thread4Class.ThreadMethod4);
3: thread4.Start();
這種方法可以在對線程操作有封裝要求的情況下使用。
3、前台線程與后台線程
只要有一個前台線程在運行,應用程序的進程就在運行。如果有多個前台線程在運行,盡管Main方法結束了,應用程序進程仍然是激活的,直到所有前台線程結束。最后一個前台線程結束會使所有后台線程一起結束,並且應用程序進程結束。在默認情況下,Thread實例是前台進程,除非在創建Thread實例時設置IsBackground屬性為true。
4、優先級
前面提到線程的調度由操作系統控制,Thread.Priority屬性可以影響調度的順序。需要注意的是,給線程指定Priority會降低其它線程的運行概率,最好是根據需要,短暫改變優先級。
Thread類有用法就簡要介紹到這,更多關於Thread類的信息,請參閱MSDN。
參考資料:《C#高級編程》
本文源代碼: