如何创建和终止线程(MSDN)
- 创建线程:
- 创建一个Worker对象和一个实例;
- 线程对象被配置为:通过将Worker.DoWork的引用传递给Thread构造函数,来将该方法用作入口点。代码如下:
Worker workerObject = new Worker(); Thread workerThread = new Thread(workerObject.DoWork);
此时,尽管辅助线程对象存在并且已经配置,但未创建实验的辅助线程。只有当调用start方法后,才会创建实际的辅助线程。代码如下:
workerThread.Start();
为了保证辅助线程执行之前不会被主线程终止,主线程将一直循环。代码如下:
while (!workerThread.IsAlive);
为了保证辅助线程能执行若干次循环主线程再sleep1毫秒。
Thread.Sleep(1);
终止线程:
之后主线程通知辅助线程该终止了:
workerObject.RequestStop();
RequestStop 方法只是将 true 赋给 _shouldStop 数据成员。由于此数据成员由 DoWork 方法来检查,因此这会间接导致 DoWork 返回,从而终止辅助线程。但是,需要注意:DoWork 和 RequestStop 将由不同线程执行。DoWork 由辅助线程执行,而 RequestStop 由主线程执行,因此 _shouldStop 数据成员声明为 volatile,如下所示:
private volatile bool _shouldStop;
通过将 volatile 与 _shouldStop 数据成员一起使用,可以从多个线程安全地访问此成员,而不需要使用正式的线程同步技术,但这仅仅是因为 _shouldStop 是 bool。这意味着只需要执行单个原子操作就能修改 _shouldStop。但是,如果此数据成员是类、结构或数组,那么,从多个线程访问它可能会导致间歇的数据损坏。假设有一个更改数组中的值的线程。Windows 定期中断线程,以便允许其他线程执行,因此线程会在分配某些数组元素之后和分配其他元素之前被中断。这意味着,数组现在有了一个程序员从不想要的状态,因此,读取此数组的另一个线程可能会失败。
然后主线程等待辅助线程终止,用join方法:
workerThread.Join();
然后主线程显示一条消息后退出。
完整代码:
using System; using System.Threading; public class Worker { // This method will be called when the thread is started. public void DoWork() { while (!_shouldStop) { Console.WriteLine("worker thread: working..."); } Console.WriteLine("worker thread: terminating gracefully."); } public void RequestStop() { _shouldStop = true; } // Volatile is used as hint to the compiler that this data // member will be accessed by multiple threads. private volatile bool _shouldStop; } public class WorkerThreadExample { static void Main() { // Create the thread object. This does not 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 1 millisecond to // allow the worker thread to do some work: Thread.Sleep(1); // Request that the worker thread stop itself: workerObject.RequestStop(); // Use the Join method to block the current thread // until the object's thread terminates. workerThread.Join(); Console.WriteLine("main thread: Worker thread has terminated."); } }