C#创建和终止线程
2013-02-18 23:14
483 查看
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."); } }
相关文章推荐
- 如何:创建和终止线程(C# 编程指南--MSDN)
- 【c#】关于终止以及删除主进程创建的线程以及进程的方法
- 如何:创建和终止线程(C# 编程指南)
- c# 创建、终止线程
- 如何:创建和终止线程(C# 编程指南)
- 【转】C# 创建 终止线程
- 如何:创建和终止线程(C# 编程指南)
- 如何:创建和终止线程(C# 编程指南)
- 如何:创建和终止线程(C# 编程指南)
- 如何:创建和终止线程(C# 编程指南)
- C# 多线程编程 - 使用Thread类创建线程
- C# 创建线程
- c#创建带参数的线程
- 多线程编程-线程的创建和终止
- C# 线程间操作无效: 从不是创建控件“receivemsg”的线程访问它。
- 线程的创建、终止、等待
- linux c之使用pthread_create创建线程pthread_join等待线程和pthread_exit终止线程总结
- 多线程编程-线程的创建和终止
- c# 终止线程
- linux c学习笔记----线程创建与终止