【转】C# 创建 终止线程
2007-08-07 12:31
417 查看
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."); } }
示例输出
main thread: starting worker thread... worker thread: working... worker thread: working... worker thread: working... worker thread: working... worker thread: working... worker thread: working... worker thread: working... worker thread: working... worker thread: working... worker thread: working... worker thread: working... worker thread: terminating gracefully... main thread: worker thread has terminated
请参见
任务
“线程”示例参考
线程处理(C# 编程指南)使用线程处理(C# 编程指南)
volatile(C# 参考)
Thread
Mutex
Monitor
Start
IsAlive
Sleep
Join
Abort
概念
C# 编程指南其他资源
托管线程处理线程示例
相关文章推荐
- 如何:创建和终止线程(C# 编程指南--MSDN)
- 如何:创建和终止线程(C# 编程指南)
- C#创建和终止线程
- 【c#】关于终止以及删除主进程创建的线程以及进程的方法
- 如何:创建和终止线程(C# 编程指南)
- 如何:创建和终止线程(C# 编程指南)
- c# 创建、终止线程
- 如何:创建和终止线程(C# 编程指南)
- 如何:创建和终止线程(C# 编程指南)
- 如何:创建和终止线程(C# 编程指南)
- 猎豹MFC--进程和线程--创建线程AfxBeginThread() SetDlgItemInt()线程暂停继续终止
- C# 多线程编程 - 使用委托创建线程
- 在内核模式下创建和终止线程
- delphi线程的创建、挂起、激活与终止
- 黄聪:BackGroundWorker解决“线程间操作无效: 从不是创建控件的线程访问它” (C# VS2008)
- C#线程间操作无效: 从不是创建控件“dataGridView1”的线程访问它
- 从不是创建控件的线程访问(C# winFrom)
- JAVA笔记13__创建线程/线程休眠/等待线程终止/线程中断/守护线程
- 线程---创建,终止
- C#当线程停止后,由线程创建的定时器会继续执行