一个最简单的线程问题 public class Alpha { public void Beta() { while (true) { Console.WriteLine("Alpha.Beta is running in its own thread."); } } } class Program { static void Main(string[] args) { Console.WriteLine("Thread Start/Stop/Join Sample"); Alpha oAlpha = new Alpha(); Thread oThread = new Thread(new ThreadStart(oAlpha.Beta)); oThread.Start(); while (!oThread.IsAlive) Thread.Sleep(1); oThread.Suspend(); -----------------(1)挂起线程 oThread.Join(); -----------------(2)这是干什么? 不懂,希望能有高人解释。 oThread.Resume(); -----------------(3)恢复现程,如果把这句话省略,程序不直停在这里,不能向下走,为什么?? Console.WriteLine("Alpha.Beta has finished"); try { Console.WriteLine("Try to restart the Alpha.Beta thread"); oThread.Resume(); -----------------(4)恢复现程,本来是想把(3)那里删除,在这里恢复线程,可是如果(3)那里取消,根本进不到这里来,为什么?? } catch (ThreadStateException) { Console.Write("ThreadStateException trying to restart Alpha.Beta. "); Console.WriteLine("Expected since aborted threads cannot be restarted."); Console.ReadLine(); } } }
------解决方案-------------------- oThread.Join(); 在继续执行标准的 COM 和 SendMessage 消息泵处理期间,阻塞调用线程,直到某个线程终止为止 Main函数执行到这的时候不会继续执行下一条语句,会等到oThread线程执行结束,Main才继续执行。 因为有oThread.Join();的存在,而且你线程函数是死循环不退出,所以后面的代码都不执行。