公司項目有可能採用C#編寫,如果用到,必然會涉及到多線程技術,基本的概念都是相同的,差別是具體的代碼。
在C#中,線程函數執行被封裝在類中,通過類對象的Start函數啟動線程執行函數。線程類Thread接受的是一個ThreadStart的delegate類型對象,具體代碼應該如下:
1 using System;
2 using System.Collections.Generic;
3 using System.Linq;
4 using System.Text;
5 using System.Threading;
6
7 namespace MultiThreadTest
8 {
9 class Program
10 {
11 static void Main(string[] args)
12 {
13 Thread thread1 = new Thread(
14 delegate()
15 {
16 Console.WriteLine("Hello Here!");
17 }
18 );
19 Thread thread2 = new Thread(
20 () => // lambda 運算式
21 {
22 Console.WriteLine("Well then goodbye!\n");
23 }
24 );
25
26 thread1.Start();
27 thread2.Start();
28 }
29 }
30 }
31
通常在多線程中,我們需要等待所有的線程都結束,系統才會等待運行退出。這個時候,可以調用線程對象的Join函數,該函數線上程達到尾部結束的時候,會進行線程返回。
當線程個數很多的時候,不帶參數的Join函數需要多次調用,非常費時費勁,這個時候,可以調用帶時間參數的Join函數,當超過時間後,系統強制結束線程運行,如下面的代碼:
1 if ( !thread.Join(30000))
2 {
3 thread.Abort();
4 }
之前處理的線程函數,都無法對資料狀態進行儲存處理,這樣,對於複雜應用顯然不是特別適合,C#的Thread採用ThreadStart委託方式,可以很好的解決這個問題:
代碼 1 class ThreadedTask{
2 string _whatToSay;
3 public ThreadedTask(string whatToSay){
4 _whatToSay = whatToSay;
5 }
6
7 public void MethodToRun(){
8 Console.WriteLine("I am babbling ( " + _whatToSay + " )");
9 }
10 }
11
12
13 ThreadedTask task = new ThreadedTask("hello");
14
15 Thread thread = new Thread(
16 new ThreadStart(task.MethodToRun)
17 );
18 thread.Start();
字串hello被存在類中,通過委託的方式將MethodToRun方法委託到線程內部,然後調用Start函數,這個時候,儲存到類中的資料也可以被準確擷取出來。