当前位置: 移动技术网 > IT编程>开发语言>c# > C#多线程ThreadPool线程池详解

C#多线程ThreadPool线程池详解

2019年07月18日  | 移动技术网IT编程  | 我要评论

简单说明一下:

线程池可以看做容纳线程的容器;一个应用程序最多只能有一个线程池;threadpool静态类通过queueuserworkitem()方法将工作函数排入线程池; 每排入一个工作函数,就相当于请求创建一个线程;

线程池的作用:

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

一些使用例子:

实例一:

using system;
using system.collections.generic;
using system.linq;
using system.text;

namespace threadpooldemo
{
 class program
 {
  static void main(string[] args)
  {
   system.threading.threadpool.queueuserworkitem(new system.threading.waitcallback(testthreadpool),new string[] {"drsw","sfs","sdfs"});
   console.readkey();
  }

  public static void testthreadpool(object state)
  {
   string[] arry = state as string[]; //传过来的参数值
   int workerthreads = 0;
   int completionportthreads = 0;
   system.threading.threadpool.getmaxthreads(out workerthreads, out completionportthreads);

   console.write(datetime.now.tostring() + "--" + arry[0] + "----workerthreads=" + workerthreads + "----completionportthreads=" + completionportthreads);
  }
 }
}

上述代码运行结果:

使用例子二:

using system;
using system.collections.generic;
using system.linq;
using system.text;

namespace threadpooldemo
{
 class program
 {
  static void main(string[] args)
  {
   system.threading.threadpool.queueuserworkitem(new system.threading.waitcallback(testthreadpool));
   console.readkey();
  }

  public static void testthreadpool(object state)
  {
   int workerthreads = 0;
   int completionportthreads = 0;
   system.threading.threadpool.getmaxthreads(out workerthreads, out completionportthreads);

   console.write(datetime.now.tostring() + "----workerthreads=" + workerthreads + "----completionportthreads=" + completionportthreads);
  }
 }
}

上述代码运行结果:

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网