网站首页 网站建设 IT知识 IT知识教程 C#多线程ThreadPool线程池详解

C#多线程ThreadPool线程池详解

2021-05-20 21:22:40

简单说明一下:

线程池可以看做容纳线程的容器;一个应用程序最多只能有一个线程池;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); } }}

上述代码运行结果:

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

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。 如涉及版权问题,请提交至online#300.cn邮箱联系删除。

以上产品还未完全满足我的所有需求,在下方提交我的专属需求
我的专属需求:
*手机号:
*验证码:
img
咨询报价
现在咨询
img

在线咨询

建站在线咨询

img

微信咨询

扫一扫添加
动力姐姐微信

img
img

TOP