C# ThreadPool之QueueUserWorkItem使用案例详解
程序员文章站
2022-03-12 22:37:22
先看代码://设置可以同时处于活动状态的线程池的请求数目。 bool pool = threadpool.setmaxthreads(8, 8);if (pool) { threadpool.q...
先看代码:
//设置可以同时处于活动状态的线程池的请求数目。 bool pool = threadpool.setmaxthreads(8, 8); if (pool) { threadpool.queueuserworkitem(o => this.dosomethinglong("参数1")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数2")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数3")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数4")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数5")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数6")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数7")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数8")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数9")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数10")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数11")); };
上面代码先设置线程池中最大并发量为8个,然后通过queueuserworkitem向线程池中添加11个方法,运行,输出结果:
可以看出,先运行了8个,当有一个任务结束后线程池中有空闲线程时,排队的下一个任务才会执行,
把最大并发量改成9试试:
{ //设置可以同时处于活动状态的线程池的请求数目。 bool pool = threadpool.setmaxthreads(9, 9); if (pool) { threadpool.queueuserworkitem(o => this.dosomethinglong("参数1")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数2")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数3")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数4")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数5")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数6")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数7")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数8")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数9")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数10")); threadpool.queueuserworkitem(o => this.dosomethinglong("参数11")); }; }
运行结果:
果然没错,这次是先执行9个,当有空闲线程时再执行下一个
总结一下
queueuserworkitem:将方法排入队列以便执行。 此方法在有线程池线程变得可用时执行。
到此这篇关于c# threadpool之queueuserworkitem使用案例详解的文章就介绍到这了,更多相关c# threadpool之queueuserworkitem内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
下一篇: Java中的逻辑控制语句详解