线程池ThreadPool中QueueUserWorkItem的使用

先看代码:

                 //设置可以同时处于活动状态的线程池的请求数目。 
                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:将方法排入队列以便执行。 此方法在有线程池线程变得可用时执行。

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小目标一个亿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值