//创建辅助线程,并用它与主线程并行执行处理。增加功能使一个线程等待另一个线程,并正确地终止线程。
usingSystem; usingSystem.Threading; publicclass Worker { // This method will be called when thethread is started. public void DoWork() { while (!_shouldStop) { Console.WriteLine("workerthread: working..."); } Console.WriteLine("worker thread:terminating gracefully."); } public void RequestStop() { _shouldStop = true; } // Volatile is used as hint to the compilerthat this data // member will be accessed by multiplethreads. private volatile bool _shouldStop; } publicclass WorkerThreadExample { static void Main() { // Create the thread object. This doesnot start the thread. Worker workerObject = new Worker(); Thread workerThread = new Thread(workerObject.DoWork); // Start the worker thread. workerThread.Start(); Console.WriteLine("main thread:Starting worker thread..."); // Loop until worker thread activates. while (!workerThread.IsAlive); // Put the main thread to sleep for 1millisecond to // allow the worker thread to do somework: Thread.Sleep(1); // Request that the worker thread stopitself: workerObject.RequestStop(); // Use the Join method to block the currentthread // until the object's threadterminates. workerThread.Join(); Console.WriteLine("main thread:Worker thread has terminated."); } } 输出如下: mainthread: starting worker thread... workerthread: working... workerthread: working... workerthread: working... workerthread: working... workerthread: working... workerthread: working... workerthread: working... workerthread: working... workerthread: working... workerthread: working... workerthread: working... worker thread:terminating gracefully... mainthread: worker thread has terminated
|