线程全部执行完了,但是 if (workerThreads == maxWordThreads) 这个判断怎么也不成立,
判断方法是 当线程池的可用线程数 == 线程池最大线程数时 为子线程全部执行完成,
大家帮我看看问题出在哪儿了
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections.Generic; using System.Threading; namespace Ex.Tester.Threads { [TestClass] public class ThreadPoolTester { /// <summary> /// /// </summary> [TestMethod] public void TestCheckThreadPoolStatus() { //启动多线程 ThreadPoolTest.RunWork(); //检查线程是否执行完成 List<string> successList = null; int len = 0; do { successList = ThreadPoolTest.SuccessList; len = successList == null ? 0 : successList.Count; Thread.Sleep(1000); } while (!ThreadPoolTest.IsFinish); } class ThreadPoolTest { private static object m_lock = new object(); private static object m_lock_check = new object(); public static List<string> SuccessList = new List<string>(); private static string msg = ""; public static bool IsFinish = false; /// <summary> /// 每秒检次一次线程池的状态 /// </summary> static RegisteredWaitHandle m_Rhw = ThreadPool.RegisterWaitForSingleObject( new AutoResetEvent(false), new WaitOrTimerCallback(CheckThreadPool), null, 1000, false); public static void CheckThreadPool(object state, bool timeout) { lock (m_lock_check) { int workerThreads = 0; //可用辅助线程的数目。 int maxWordThreads = 0; //线程池中辅助线程的最大数目。 int completionPortThreads = 0; //线程池中异步 I/O 线程的最大数目。 ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); ThreadPool.GetMaxThreads(out maxWordThreads, out completionPortThreads); //当可用的线数与池程池最大的线程相等时表示线程池中所有的线程已经完成 if (workerThreads == maxWordThreads) { //当执行此方法后CheckThreadPool将不再执行 m_Rhw.Unregister(null); IsFinish = true; } } } private static void DoWork(object par) { lock (m_lock) { SuccessList.Add(par.ToString()); } } public static void RunWork() { ThreadPool.SetMaxThreads(10, 5); for (int i = 0; i < 20; i++) { int workerThreads = 0; int completionPortThreads = 0; //线程池中异步 I/O 线程的最大数目。 ThreadPool.GetAvailableThreads(out workerThreads, out completionPortThreads); ThreadPool.QueueUserWorkItem(new WaitCallback(DoWork), "T" + i.ToString()+",r="+workerThreads+",c="+completionPortThreads); } } } } } ---- 40分