技术开发 频道

C#的多线程机制初探(2)


【IT168技术文档】

  下面我们就动手来创建一个线程,使用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();         //这里创建一个线程,使之执行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;       }     }   }
0
相关文章