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");
