线程池
Posted pilgrim
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程池相关的知识,希望对你有一定的参考价值。
线程的创建需要时间。如果存在多个任务需要完成,则可以事先创建许多线程,在应该完成任务时发出需求线程请求。线程数最好时动态的增加于减少。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选项。
以上是关于线程池的主要内容,如果未能解决你的问题,请参考以下文章