ThreadPool不能立即启动新线程 [英] ThreadPool not starting new Thread instantly

查看:212
本文介绍了ThreadPool不能立即启动新线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#Windows服务,可以启动各种对象(类库).这些对象中的每个对象都有其自己的处理"逻辑,这些逻辑通过使用ThreadPool启动多个长时间运行的处理线程.我有一个例子,就像这样:

I have a C# Windows Service that starts up various objects (Class libraries). Each of these objects has its own "processing" logic that start up multiple long running processing threads by using the ThreadPool. I have one example, just like this:

System.Threading.ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(WorkerThread_Processing));

这很好.我的应用程序运行正常,线程运行良好.

This works great. My app works with no issues, and my threads work well.

现在,为了进行回归测试,我正在从C#控制台应用程序而不是Windows Service启动这些相同的对象.它调用的是完全相同的代码(因为它正在调用相同的对象),但是WorkerThread_Processing方法在启动之前最多延迟20秒.

Now, for regression testing, I am starting those same objects up, but from a C# Console app rather than a Windows Service. It calls the same exact code (because it is invoking the same objects), however the WorkerThread_Processing method delays for up to 20 seconds before starting.

我进去并从ThreadPool切换到Thread,问题消失了.这里可能会发生什么?我知道我还没有超过MaxThreads计数(我正在启动最多20个线程).

I have gone in and switched from the ThreadPool to a Thread, and the issue goes away. What could be happening here? I know that I am not over the MaxThreads count (I am starting 20 threads max).

推荐答案

ThreadPool专门用于长期运行的项目(更具体地说,您甚至不必重新启动当您使用ThreadPool时,这些线程会中断,因为它的目的是将任务分散在有限数量的线程上.

The ThreadPool is specifically not intended for long-running items (more specifically, you aren't even necessarily starting up new threads when you use the ThreadPool, as its purpose is to spread the tasks over a limited number of threads).

如果任务长期运行,则应将其分解为放在ThreadPool上的逻辑部分(或使用新的Task框架),或旋转自己的Thread对象.

If your task is long running, you should either break it up into logical sections that are put on the ThreadPool (or use the new Task framework), or spin up your own Thread object.

关于原因,您遇到延迟的原因,

As to why you're experiencing the delay, the MSDN Documentation for the ThreadPool class says the following:

作为其线程管理策略的一部分,线程池在创建线程之前会延迟.因此,当许多任务在短时间内排队时,开始所有任务之前可能会有相当长的延迟.

As part of its thread management strategy, the thread pool delays before creating threads. Therefore, when a number of tasks are queued in a short period of time, there can be a significant delay before all the tasks are started.

您只知道ThreadPool尚未达到其最大线程数,而不是它实际上有多少空闲线程(如果有).

You only know that the ThreadPool hasn't reached its maximum thread count, not how many threads (if any) it actually has sitting idle.

这篇关于ThreadPool不能立即启动新线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆