开发者

threading concept

A thread should not star开发者_StackOverflowt event the start method is called.. is it possible? in c#


As this code demonstrates, the thread automatically is created in a suspended state and will not start until you call 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);
      }
   }
}

(This was created with C# on .NET 3.5, was threading different for 2.0?)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜