线程池

线程池中的线程:

  1、本身都是后台线程

  2、线程可以进行重用

线程池内部原理图

10000个线程池 VS 500个线程 执行时间

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Threading;
 7 using System.Diagnostics;
 8 
 9 namespace 线程池练习
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             Stopwatch sw = new Stopwatch();
16             sw.Start();
17             for (int i = 0; i < 500; i++)
18             {
19                 new Thread(()=> {
20                     int j = 0;
21                     j++;
22                 }).Start();
23             }
24             sw.Stop();
25             Console.WriteLine("执行时间:"+sw.Elapsed.TotalSeconds);
26             Console.ReadKey();
27         }
28     }
29 }
线程
复制代码

执行时间

复制代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 using System.Threading;
 7 using System.Diagnostics;
 8 
 9 namespace 线程池练习
10 {
11     class Program
12     {
13         static void Main(string[] args)
14         {
15             Stopwatch sw = new Stopwatch();
16             sw.Start();
17             for (int i = 0; i < 10000; i++)
18             {
19                 ThreadPool.QueueUserWorkItem((s) =>
20                 {
21                     int j = 0;
22                     j++;
23                 });
24             }
25             Console.WriteLine("执行时间:" + sw.Elapsed.TotalSeconds);
26             Console.ReadKey();
27         }
28     }
29 }
线程池
复制代码

 

 什么时候用线程池?什么时候用手动创建线程?

1、能用线程池的就用线程池,处理顺序不确定

2、我们想手动关闭线程的话,那么必须手动创建了。Abort()   Join()

3、我们需要对线程池的线程的优先级做设置的情景下,只能使用手动创建线程。

4、如果执行的线程执行时间特别长。线程池:适合做大量小运算

获取线程池最大的线程数据

1         static void Main(string[] args)
2         {
3             int numMax = 0;
4             int runNumMax = 0;
5             ThreadPool.GetMaxThreads(out numMax, out runNumMax);
6             Console.WriteLine("线程池中辅助线程的最大数目:"+numMax+ ",线程池中异步 I/O 线程的最大数目:"+runNumMax);
7             Console.ReadKey();
8         }

 

posted @   陈彦斌  阅读(267)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示