C#多線程學習(二)如何操縱一個線程

來源:互聯網
上載者:User

下面我們就動手來建立一個線程,使用Thread類建立線程時,只需提供線程入口即可。(線程入口使程式知道該讓這個線程幹什麼事)

在C#中,線程入口是通過ThreadStart代理(delegate)來提供的,你可以把ThreadStart理解為一個函數指標,指向線程要執行的函數,當調用Thread.Start()方法後,線程就開始執行ThreadStart所代表或者說指向的函數。

開啟你的VS.net,建立一個控制台應用程式(Console Application),編寫完全控制一個線程的程式碼範例:

//ThreadTest.cs
using System;
using System.Threading;
namespace ThreadTest
{
   public class Alpha
   {
       public void Beta()
       {
         while (true)
         {
           Console.WriteLine("Alpha.Beta is running in its own thread.");
         }
       }
   };
  public class Simple
   {
       public static int Main()
       {
         Console.WriteLine("Thread Start/Stop/Join Sample");
Alpha oAlpha = new Alpha();
         file://這裡建立一個線程,使之執行Alpha類的Beta()方法
         Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));
         oThread.Start();
         while (!oThread.IsAlive)
         Thread.Sleep(1);
         oThread.Abort();
         oThread.Join();
         Console.WriteLine();
         Console.WriteLine("Alpha.Beta has finished");
         try
         {
           Console.WriteLine("Try to restart the Alpha.Beta thread");
           oThread.Start();
         }
         catch (ThreadStateException)
         {
           Console.Write("ThreadStateException trying to restart Alpha.Beta. ");
           Console.WriteLine("Expected since aborted threads cannot be restarted.");
           Console.ReadLine();
         }
         return 0;
       }
   }
}

這段程式包含兩個類Alpha和Simple,在建立線程oThread時我們用指向Alpha.Beta()方法的初始化了ThreadStart代理(delegate)對象,當我們建立的線程oThread調用oThread.Start()方法啟動時,實際上程式啟動並執行是Alpha.Beta()方法:

Alpha oAlpha = new Alpha();

Thread oThread = new Thread(new ThreadStart(oAlpha.Beta));

oThread.Start();

然後在Main()函數的while迴圈中,我們使用靜態方法Thread.Sleep()讓主線程停了1ms,這段時間CPU轉向執行線程oThread。然後我們試圖用Thread.Abort()方法終止線程oThread,注意後面的oThread.Join(),Thread.Join()方法使主線程等待,直到oThread線程結束。你可以給Thread.Join()方法指定一個int型的參數作為等待的最長時間。之後,我們試圖用Thread.Start()方法重新啟動線程oThread,但是顯然Abort()方法帶來的後果是不可恢複的終止線程,所以最後程式會拋出ThreadStateException異常。

聯繫我們

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