int n_max_thread = 2; System.Threading.AutoResetEvent wait_sync = new System.Threading.AutoResetEvent(false); // 用来控制:并发最大个数线程=n_max_thread System.Threading.AutoResetEvent wait_main = new System.Threading.AutoResetEvent(false); // 用来控制:主程序的结束执行,当所有任务线程执行完毕 var m_Events = new ManualResetEvent(false); System.Threading.ThreadPool.SetMaxThreads(2, 2); for (int i = 0; i < 100; i++) { if (ThreadHelper.MaxThreadCount>= n_max_thread) // -1 表示第max个线程尚未开始 { //log_wait.Info(string.Format("thread n= {0},for i= {1}", dic_Thread.Count, i + 1)); wait_sync.WaitOne(10*1000); // 每次并发10个线程,等待处理完毕后,在发送下一次并发线程 } else { wait_sync.Set(); } System.Threading.ThreadPool.QueueUserWorkItem(state => { Thread.Sleep(new Random().Next(5,10)*1000); Console.WriteLine("over"+Thread.GetCurrentProcessorId()); }, null); } Console.WriteLine("完成"); Console.WriteLine("数量"+ ThreadHelper.MaxThreadCount); Console.ReadKey();
来源:迪客赚(QQ/微信:313919848),转载请保留出处和链接!如有侵权或出处有误请联系网站客服,我们会第一时间为你处理。