C#如何判断线程池中所有的线程是否已经完成之Demo
1 start: 2 3 System.Threading.RegisteredWaitHandle rhw = null; 4 new Action(() => 5 { 6 for (var i = 0; i < 30; i++) { 7 new Action<int>((index) => 8 { 9 System.Threading.Thread.Sleep(1000); 10 Console.WriteLine(System.Threading.Thread.CurrentThread.Name + "执行完毕" + index); 11 }).BeginInvoke(i, null, null); 12 } 13 }).BeginInvoke(null, null); 14 rhw = System.Threading.ThreadPool.RegisterWaitForSingleObject(new System.Threading.AutoResetEvent(false), new System.Threading.WaitOrTimerCallback((obj, b) => 15 { 16 int workerThreads = 0; 17 int maxWordThreads = 0; 18 //int 19 int compleThreads = 0; 20 System.Threading.ThreadPool.GetAvailableThreads(out workerThreads, out compleThreads); 21 System.Threading.ThreadPool.GetMaxThreads(out maxWordThreads, out compleThreads); 22 //Console.WriteLine(workerThreads); 23 //Console.WriteLine(maxWordThreads); 24 //当可用的线数与池程池最大的线程相等时表示线程池中所有的线程已经完成 25 if (workerThreads == maxWordThreads) 26 { 27 //当执行此方法后CheckThreadPool将不再执行 28 rhw.Unregister(null); 29 //此处加入所有线程完成后的处理代码 30 Console.WriteLine("f"); 31 rhw = null; 32 } 33 }), null, 100, false); 34 while (rhw != null) { } 35 System.Threading.Thread.Sleep(10000) ; 36 goto start; 37 Console.WriteLine("finished");