what#39;s the proper way to use a ThreadPool?(使用 ThreadPool 的正确方法是什么?)
问题描述
如果我对 ThreadPool 工作方式的理解是正确的,那么它的目的之一就是限制在给定时间可以创建的进程中的工作线程数.例如,如果您将 MaxThreads 设置为 5,然后调用 QueueUserWorkItem 30 次,则会向 ThreadPool 发出 30 个请求,但其中只有 5 个请求会被新线程处理,而其他 25 个请求将被添加到队列中并在之前的请求完成且现有线程可用时一次提供一个服务.
If my understanding of the way the ThreadPool works is correct, one of its purposes is to limit the number of worker threads within a process that can be created at a given time. For example, if you set MaxThreads to 5 and then call QueueUserWorkItem 30 times, 30 requests will be made to the ThreadPool, but only 5 of those requests will be serviced by a new thread, while the other 25 requests will be added to the queue and serviced one at time as previous requests complete and existing threads becomes available.
然而,在下面的代码中,对 Thread.Sleep(-1) 的调用保证 DoSomething() 方法永远不会返回,这意味着当前线程永远不会对后续请求可用.
In the code below, however, the call to Thread.Sleep(-1) guarantees that the DoSomething() method will never return, meaning that the current thread will never become available to subsequent requests.
但我对 ThreadPool 工作方式的理解并不正确,因为如果正确,下面的代码将只打印数字 0-4,而不是 0-29.
But my understanding of the way a ThreadPool works cannot be correct, because if it were correct the code below would print only the numbers 0-4, rather than 0-29.
谁能解释一下 ThreadPool 是如何工作的,以及为什么下面的代码没有做我认为应该做的事情?
Can someone please explain how the ThreadPool works and why the below code isn't doing what I thought it should be doing?
static void DoSomething(object n)
{
Console.WriteLine(n);
Thread.Sleep(-1);
}
static void Main(string[] args)
{
ThreadPool.SetMaxThreads(5, 5);
for (int x = 0; x < 30; x++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(DoSomething), x);
}
Console.Read();
}
推荐答案
ThreadPool.SetMaxThreads(5, 5)
表示活动线程数为5(如果你有超过5个cpu核心),并不意味着ThreadPool只能创建5个线程.ThreadPool 最大线程数 = CPU Core * 250.
means the number of active thread is 5 (if you have more than 5 cpu core), does not mean that the ThreadPool can only create 5 threads. The ThreadPool maximum number of threads = CPU Core * 250.
Thread.Sleep
之后,线程处于非活动状态,不会影响其他线程的执行.
After Thread.Sleep
, the thread is inactive, so it will not affect the execution of other threads.
这篇关于使用 ThreadPool 的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 ThreadPool 的正确方法是什么?
基础教程推荐
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- MS Visual Studio .NET 的替代品 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何激活MC67中的红灯 2022-01-01