C#多线程ThreadPool线程池详解
发布时间:2020-12-15 06:02:58 所属栏目:百科 来源:网络整理
导读:简单说明一下: 线程池可以看做容纳线程的容器;一个应用程序最多只能有一个线程池;ThreadPool静态类通过QueueUserWorkItem()方法将工作函数排入线程池; 每排入一个工作函数,就相当于请求创建一个线程; 线程池的作用: 1、线程池是为突然大量爆发的线程
简单说明一下: 线程池可以看做容纳线程的容器;一个应用程序最多只能有一个线程池;ThreadPool静态类通过QueueUserWorkItem()方法将工作函数排入线程池; 每排入一个工作函数,就相当于请求创建一个线程; 线程池的作用: 1、线程池是为突然大量爆发的线程设计的,通过有限的几个固定线程为大量的操作服务,减少了创建和销毁线程所需的时间,从而提高效率。 一些使用例子: 实例一: 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); } } } 上述代码运行结果: 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程小技巧。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读