.NET簡談組件程式設計之(多線程與並發管理一)

來源:互聯網
上載者:User

 

由於多線程的內容比較多我會用幾篇文章來講解。

多線程在我們日常開發過程中用的很多,上一篇“.NET簡談組件程式設計之(非同步委託)”詳細的講解了基於委託的多線程使用,委託是基於後台線程池的原理,這篇文章將主要介紹直接使用Thread對象來實現多線程。

當然使用Thread沒有使用Delegate那麼容易,畢竟多線程跟非同步呼叫是兩個相差很大的技術方向,我也是略懂點皮毛,在此獻醜給大家,如有講的不對的地方還請指出。[王清培著作權,轉載請給出署名]

我們先來理解幾個概念,以方便我們學習。

後台線程與前台線程

前台線程:什麼叫前台線程,就是我們使用預設的Thread建立出來的沒有進行IsBackground屬性設定的都是前台線程,因為預設IsBackground是false。前台線程是明確任務的,也就是任何一個前台線程沒有結束之前程式是不會自動結束的,除非強制關閉應用程式。

後台線程:後台線程是針對前台線程來說的,將Thread.IsBackground設定為true就是後台線程,後台線程是為前台線程服務的,就是說後台線程沒有很強的生命力,只要前台線程都結束了,後台線程都強制結束,哪怕任務還沒有完成都不行。所以我們在使用的時候要看情況進行選擇。[王清培著作權,轉載請給出署名]

線程的切換

我們來看一段代碼,以方便引入主題。

using System; using System.Collections.Generic; using System.Text; using System.Threading;using System.Runtime.Remoting;  using System.Runtime.Remoting.Contexts;   namespace ConsoleApplication1.多線程和並發管理  {     public class MyClass      {          public void ShowMessage()          {              Thread currentthread = Thread.CurrentThread;              Console.WriteLine(currentthread.Name + currentthread.ManagedThreadId);          }                }  }  

這是一段很簡單的代碼,就是一個ShowMessage方法,在方法裡面有一個擷取當前上下文線程的靜態屬性Thread.CurrentThread,然後輸入該線程的名稱和託管ID號;

namespace ConsoleApplication1.多線程和並發管理  {      public static class Program      {          static void Main(string[] args)          {              Thread currentthread = Thread.CurrentThread;              currentthread.Name = "主線程";              Console.WriteLine(currentthread.Name + currentthread.ManagedThreadId);               MyClass myclass = new MyClass();              ThreadStart start = new ThreadStart(myclass.ShowMessage);             Thread thread = new Thread(start);              thread.Name = "子線程";              thread.Start();               Thread.Sleep(1000);//休眠,線程切換              Console.WriteLine(currentthread.Name + currentthread.ManagedThreadId);              Console.Read();      }      }     }  

這是調用代碼,我先給主線程起個名字,然後輸出。我建立了一個thread線程,這是子線程,調用我們上面定義的方法,用同樣的Thread.CurrentThread來擷取當前上下文線程,最後讓主線程休眠一秒鐘。

通過該圖我們能清楚的看見,系統在後台自動幫我們進行線程切換,用同一個靜態變數就可以擷取到當前線程對象。

通過Sleep方法是讓當前線程休眠指定的時間斷,哪怕當前線程正在CPU上運行著,一旦調用Sleep就立刻放棄CPU給它的時間片,進入阻塞狀態。

 [一個線程僅僅是一個進程中的執行路徑]

其實線程是執行路徑,系統中維護著一個執行路徑的命令集合,當我們開啟了多個線程的時候其實就是往著個命令集合中存放了很多要執行的命令而已,換句話說命令就是線程隊列,用CPU 對它進行時間片的執行。

那麼線程是肯定需要一系列的狀態的,這個狀態時有OS幫我們維持著,因為線程是屬於核心層的對象,只有OS才能即時監控著。我們只需要用就行了,有興趣的朋友可以參考,傑夫瑞 (Jeffrey Richter)《Windows核心編程(第5版)》  一書。

讓線程等待而不是切換

Sleep是強制放棄CPU的時間片,然後重新和其他線程一起參與CPU的競爭。用Sleep是會讓線程放棄CPU的使用權,而如果我們換成  Thread.SpinWait(100000000),是不會放棄CPU的使用權的,只是讓CPU去執行一段沒有用的代碼,當時間結束之後能立馬繼續執行,而不是和重新參與CPU的競爭。

在系統資源很豐富的情況下可能這點並不重要,但是在資源缺乏,CPU又不是很好的時候,我想這點還是能改善點效能的。

在此不得不提一個重要的概念,就是線程的調用方和線程主體,線程的調用方就是線程的用戶端,是另外一個線程,而不是當前線程主體。

Thread.Join()連接線程

join方法從字面理解是串連的意思,剛接觸真的很難理解,什麼叫串連。請看一段代碼:

Thread currentthread = Thread.CurrentThread;     currentthread.Name = "主線程";        Console.WriteLine(currentthread.Name + currentthread.ManagedThreadId);      MyClass myclass = new MyClass();          ThreadStart start = new ThreadStart(myclass.ShowMessage);        Thread thread = new Thread(start);          thread.Name = "子線程";          thread.Start();         thread.Join();//阻塞子線程thread線程,直到子線程thread執行結束        Console.WriteLine(currentthread.Name + currentthread.ManagedThreadId);       Console.Read(); 

通過Join我們可以等待線程結束,串連的意思就是將我和我調用的thread線程串連起來,我要等你結束之後我才能繼續執行,這裡就是主線程和子線程的關係,只有子線程技術之後,主線程才能繼續執行。

Thread.Abort終止線程

利用Abort可以終止一個在執行的線程,但是Abort會線上程上引發一個ThreadAbortException異常。

public void DoWork()    {                try             {                   int i = 0;             while (true)            {                     Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "|" + i++);                     if (i == 100)                     {                         Console.WriteLine("---------------------------------------------");                          Console.Read();                       break;//退出當前線程執行,盡量不要用Abort結束                     }                 }             }             catch (ThreadAbortException err)                 {                     Console.WriteLine(err.Message + "11");             }      } 
Thread currentthread = Thread.CurrentThread;      Console.WriteLine(currentthread.Name + currentthread.ManagedThreadId);       MyClass myclass = new MyClass();         ThreadStart start = new ThreadStart(myclass.DoWork);       Thread thread = new Thread(start);          thread.Start();            Thread.Sleep(5000);          Console.WriteLine(currentthread.Name + currentthread.ManagedThreadId + "是否終止子線程");        thread.Abort();       Console.Read(); 

Thread.IsBackground = true後台線程

通過設定IsBackground可以讓線程處於後台線程,只要前台線程結束,那麼後台線程自動終止。

public void DoWork()         {             try            {                       int i = 0;                    while (true)                 {                    Console.WriteLine(Thread.CurrentThread.ManagedThreadId + "|" + i++);                     //if (i == 100)                     //{                     //    Console.WriteLine("---------------------------------------------");                     //    Console.Read();                     //    break;//退出當前線程執行,盡量不要用Abort結束                     //}                      }             }             catch (ThreadAbortException err)             {                 Console.WriteLine(err.Message + "11");             } 

我們將一段代碼注釋掉。

Thread currentthread = Thread.CurrentThread;     Console.WriteLine(currentthread.Name + currentthread.ManagedThreadId);      MyClass myclass = new MyClass();           ThreadStart start = new ThreadStart(myclass.DoWork);     Thread thread = new Thread(start);    thread.IsBackground = true;      thread.Start();           Thread.Sleep(2000);           Console.WriteLine(currentthread.Name + currentthread.ManagedThreadId); 

 

這是調用代碼。只要前台線程不結束,後台線程就一直執行。如果我們在最後加上一段Console.ReadLine();代碼,那麼後台線程會始終運行著。

 

這篇文章就先結束了,下一篇我們將學習關於同步域和內容相關的概念。 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.