下面我们就动手来创建一个线程,使用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;
      }
    }
  }

这段程序包含两个类AlphaSimple,在创建线程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异常。

posted on 2006-10-05 21:23  chinaprg  阅读(712)  评论(0编辑  收藏  举报