这篇文章主要介绍了C# 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:将方法排入队列以便执行。 此方法在有线程池线程变得可用时执行。
到此这篇关于C# ThreadPool之QueueUserWorkItem使用案例详解的文章就介绍到这了,更多相关C# ThreadPool之QueueUserWorkItem内容请搜索得得之家以前的文章希望大家以后多多支持得得之家!
织梦狗教程
本文标题为:C# ThreadPool之QueueUserWorkItem使用案例详解


基础教程推荐
猜你喜欢
- C#通过标签软件Bartender的ZPL命令打印条码 2023-05-16
- 实例详解C#实现http不同方法的请求 2022-12-26
- C#中 Json 序列化去掉null值的方法 2022-11-18
- C#获取指定目录下某种格式文件集并备份到指定文件夹 2023-05-30
- C#中的Linq to JSON操作详解 2023-06-08
- c# – USING块在网站与Windows窗体中的行为不同 2023-09-20
- Unity shader实现高斯模糊效果 2023-01-16
- C# 解析XML和反序列化的示例 2023-04-14
- C#调用摄像头实现拍照功能的示例代码 2023-03-09
- Unity 如何获取鼠标停留位置下的物体 2023-04-10