线程池
线程的创建需要时间。如果存在多个任务需要完成,则可以事先创建许多线程,在应该完成任务时发出需求线程请求。线程数最好时动态的增加于减少。TheadPool类可以托管线程列表,这个类能动态增加于减少线程的线程数,直到最大线程数----可配置。在四核CPU中,默认为1023个工作线程和1000个I/O线程。也可以指定创建线程池时应该立即启动的最小线程数,以及可用最大线程数。如果有新的任务,但是线程池中已没有闲于线程,那么新任务需要排队,等待线程完成其任务。如下示例:
static void Main() { int nWorkerThreads; int nCompletionPortThreads; ThreadPool.GetMaxThreads(out nWorkerThreads, out nCompletionPortThreads); Console.WriteLine("Max worker threads: {0}, I/O completion threads: {1}", nWorkerThreads, nCompletionPortThreads for (int i = 0; i < 10; i++) { ThreadPool.QueueUserWorkItem(JobForAThread); //WaitCallback类型委托:线程池线程要执行的回调方法 } Thread.Sleep(3000); /*******************输出结果***************************** * Max worker threads: 1023, I/O completion threads: 1000 * loop 0, running inside pooled thread 3 * loop 0, running inside pooled thread 4 * loop 0, running inside pooled thread 7 * loop 0, running inside pooled thread 6 * loop 0, running inside pooled thread 8 * loop 0, running inside pooled thread 9 * loop 0, running inside pooled thread 10 * loop 0, running inside pooled thread 5 * loop 1, running inside pooled thread 6 * loop 1, running inside pooled thread 4 * loop 1, running inside pooled thread 7 * loop 1, running inside pooled thread 3 * loop 1, running inside pooled thread 5 * loop 1, running inside pooled thread 8 * loop 1, running inside pooled thread 10 * loop 1, running inside pooled thread 9 * loop 2, running inside pooled thread 6 * loop 2, running inside pooled thread 4 * loop 2, running inside pooled thread 5 * loop 2, running inside pooled thread 7 * loop 2, running inside pooled thread 3 * loop 2, running inside pooled thread 8 * loop 2, running inside pooled thread 10 * loop 2, running inside pooled thread 9 * loop 0, running inside pooled thread 6 * loop 0, running inside pooled thread 4 * loop 1, running inside pooled thread 6 * loop 1, running inside pooled thread 4 * loop 2, running inside pooled thread 6 * loop 2, running inside pooled thread 4 * *******************************************************/ } static void JobForAThread(object state) { for (int i = 0; i < 3; i++) { Console.WriteLine("loop {0}, running inside pooled thread {1}", i, Thread.CurrentThread.ManagedThreadId); Thread.Sleep(50); } }
10个任务,只由8个线程池中的线程处理(因为CPU是8核)。线程池虽然简单,但是有如下限制:
- 线程池中所有线程都是后台线程,且不能将线程池中的线程改为前台线程。如果进程的所有前台线程都结束了,那么所有的后台线程就会停止。
- 不能给入池的线程设置优先级或者线程名称。
- 对于COM对象,入池的所有线程都是多线程单元(MTA)线程。许多COM对象都需要单线程单元(STA)线程。
- 入池的线程只能用于时间较短的任务。如果线程要一直运行,就应该使用Thread类创建一个线程,或者创建Task时使用LongRunning选项。
凡所有相,皆是虚妄。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?