四联光电智能照明论坛

标题: 浅谈ThreadPool 线程池 [打印本页]

作者: admin    时间: 2016-11-7 15:34
标题: 浅谈ThreadPool 线程池
相关概念:
    线程池可以看做容纳线程的容器;
    一个应用程序最多只能有一个线程池;
    ThreadPool静态类通过QueueUserWorkItem()方法将工作函数排入线程池;
    每排入一个工作函数,就相当于请求创建一个线程;

线程池的作用:
线程池是为突然大量爆发的线程设计的,通过有限的几个固定线程为大量的操作服务,减少了创建和销毁线程所需的时间,从而提高效率。
如果一个线程的时间非常长,就没必要用线程池了(不是不能作长时间操作,而是不宜。),况且我们还不能控制线程池中线程的开始、挂起、和中止。

什么时候使用ThreadPool?


ThreadPool 示例一 :

  1. ThreadPool_1.cs

  2. using System;
  3. using System.Text;
  4. using System.Threading;

  5. namespace 多线程
  6. {
  7.     public class Example
  8.     {
  9.         public static void Main()
  10.         {
  11.             // Queue the task.
  12.             ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc));

  13.             Console.WriteLine("Main thread does some work, then sleeps.");
  14.          
  15.             Thread.Sleep(1000);

  16.             Console.WriteLine("Main thread exits.");
  17.         }

  18.         static void ThreadProc(Object stateInfo)
  19.         {
  20.             // No state object was passed to QueueUserWorkItem,
  21.             // so stateInfo is null.
  22.             Console.WriteLine("Hello from the thread pool.");
  23.         }
  24.     }
  25. }
复制代码





ThreadPool 示例二 :

  1. ThreadPool_2.cs

  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5. using System.Threading;

  6. namespace CS_Test
  7. {
  8.     class ThreadPool_Demo
  9.     {
  10.         // 用于保存每个线程的计算结果
  11.         static int[] result = new int[10];


  12.         //注意:由于WaitCallback委托的声明带有参数,
  13.         //      所以将被调用的Fun方法必须带有参数,即:Fun(object obj)。
  14.         static void Fun(object obj)
  15.         {
  16.             int n = (int)obj;

  17.             //计算阶乘
  18.             int fac = 1;
  19.             for (int i = 1; i <= n; i++)
  20.             {
  21.                 fac *= i;
  22.             }
  23.             //保存结果
  24.             result[n] = fac;
  25.         }

  26.         static void Main(string[] args)
  27.         {
  28.             //向线程池中排入9个工作线程
  29.             for (int i = 1; i <= 9 ; i++)
  30.             {
  31.                 //QueueUserWorkItem()方法:将工作任务排入线程池。
  32.                 ThreadPool.QueueUserWorkItem(new WaitCallback(Fun),i);
  33.                 // Fun 表示要执行的方法(与WaitCallback委托的声明必须一致)。
  34.                 // i   为传递给Fun方法的参数(obj将接受)。
  35.             }

  36.             //输出计算结果
  37.             for (int i = 1; i <= 9; i++)
  38.             {
  39.                 Console.WriteLine("线程{0}: {0}! = {1}",i,result[i]);
  40.             }
  41.         }

  42.     }
  43. }
复制代码


ThreadPool的作用:






欢迎光临 四联光电智能照明论坛 (http://5xhome.com/) Powered by Discuz! X3.2