创建和终止线程的好方法
2009-12-30 11:32
471 查看
参见MSDN:http://msdn.microsoft.com/zh-cn/library/7a2f3ay4.aspx
使用一个标示位来判断线程何时终止,而不是使用Abort(强行终止线程,即使线程尚未完成任务)方法。
实例代码如下:
使用一个标示位来判断线程何时终止,而不是使用Abort(强行终止线程,即使线程尚未完成任务)方法。
实例代码如下:
using System; using System.Collections.Generic; using System.Threading; public class MyClass { public static void Main() { Console.WriteLine("Main thread is start"); ThreadTest threadTest = new ThreadTest(); Thread childThread = new Thread(threadTest.Work); childThread.Start(); for(int i=0;i<10000;i++) { if(i%50 == 0) { Console.WriteLine("Main thread is running"); } } threadTest.StopThread(); childThread.Join(); Console.WriteLine("Main thread is stop"); Console.Read(); } } public class ThreadTest { private volatile bool _threadStop; /// <summary> /// 执行内容 /// </summary> public void Work() { Console.WriteLine("Child thread is start"); while(_threadStop == false) { Console.WriteLine("Child thread is running"); } Console.WriteLine("Child thread is stop"); } /// <summary> /// 停止线程 /// </summary> public void StopThread() { _threadStop = true; } }
相关文章推荐
- 【c#】关于终止以及删除主进程创建的线程以及进程的方法
- java 多线程总结(一) 创建线程的几种方法及对终止线程运行的讨论
- 多线程篇(一)——线程的创建方法CreateThread和_beginthreadex
- 黑马程序员:创建线程的两种方法
- Java创建线程的两个方法
- 懒人的方法处理: 从不是创建控件XXX的线程访问的异常
- 线程创建方法
- Java多线程(一)——线程创建的两种方法
- 线程创建方法
- Java多线程 创建线程的两种方法
- 线程间操作无效: 从不是创建控件“”的线程访问它的解决方法
- PL/SQL 查询session杀不掉,强制终止线程的解决方法
- delphi线程的创建、挂起、激活与终止
- Java创建线程的两个方法
- 创建线程的三种方法
- “线程间操作无效:从不是创建控件“XX”的线程访问它”的解决方法
- unix环境中线程的创建与终止
- JAVA中 终止线程的方法
- delphi线程的创建、挂起、激活与终止
- 在内核模式下创建和终止线程