问题描述
如果我对 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 的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!