线程概念

时间:2009-11-05 12:05:23

标签: c#-2.0

线程不应该启动事件调用start方法..是否可能?在c#

1 个答案:

答案 0 :(得分:1)

正如此代码所示,线程会自动创建为挂起状态,直到您调用start时才会启动。

class Program
{
   static void Main(string[] args)
   {
      Worker w = new Worker();
      Console.ReadKey();
      w.Start();
      Console.ReadKey();
      w.Stop();
      Console.ReadKey();
   }
}

class Worker
{
   System.Threading.Thread workerThread;
   bool work;

   public Worker()
   {
      System.Threading.ThreadStart ts = new System.Threading.ThreadStart(DoWork);
      workerThread = new System.Threading.Thread(ts);
   }

   public void Start()
   {
      work = true;
      workerThread.Start();
   }

   public void Stop()
   {
      work = false;
   }

   private void DoWork()
   {
      while(work)
      {
         Console.WriteLine(System.DateTime.Now.ToLongTimeString());
         System.Threading.Thread.Sleep(1000);
      }
   }
}

(这是在.NET 3.5上用C#创建的,对于2.0来说线程是不同的吗?)

相关问题