C#多線程技術(一)

來源:互聯網
上載者:User

公司項目有可能採用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函數,這個時候,儲存到類中的資料也可以被準確擷取出來。

 

 

 

 

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.