为什么通过调用Task.Run和ThreadPool.QueueUserWorkItem排队到ThreadPool时线程数增加了不止一个?
Why threads count is increased by more than one when queuing to ThreadPool by calling Task.Run and ThreadPool.QueueUserWorkItem?
我试图在 Thread
:
的帮助下计算控制台应用程序中的 运行 线程数
new Thread(() =>
{
while (true)
{
Thread.Sleep(500);
Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().Threads.Count);
}
}).Start();
然后我开始了新的 Thread
,其中包含非常简单的执行逻辑。毫不奇怪,线程数增加了 1
。对于 ThreadPool.QueueUserWorkItem
它增加了 3。
并对 Task.Run(() => {...})
进行了相同的测试。令人惊讶的是,线程数增加了 4
,有时甚至增加了 5
。不幸的是,我无法理解原因。
这里是完整的测试代码:
static void Main(string[] args)
{
new Thread(() =>
{
while (true)
{
Thread.Sleep(500);
Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().Threads.Count);
}
}).Start();
//Task.Run(() =>
//{
// Thread.Sleep(5000);
//}); // thread count is 12
//new TaskFactory().StartNew(() =>
//{
// Thread.Sleep(5000);
//}); // thread count is 12
//ThreadPool.QueueUserWorkItem((onj) =>
//{
// Thread.Sleep(5000);
//}); // thread count is 9
//new Thread(() =>
//{
// Thread.Sleep(5000);
//}).Start(); // thread count is 7
Console.ReadLine();
}
我的问题是,为什么 运行 new Task 会增加 4 或 5 个线程数?为什么线程池的排队工作项会使线程数增加 3?
线程池使用 complicated mechanism 来确定将有多少个线程 运行。
当您通过调用 QueueUserItem
或创建 Task
将工作排队到线程池时,线程池会使用默认的初始线程数进行初始化,通常为四个。
我试图在 Thread
:
new Thread(() =>
{
while (true)
{
Thread.Sleep(500);
Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().Threads.Count);
}
}).Start();
然后我开始了新的 Thread
,其中包含非常简单的执行逻辑。毫不奇怪,线程数增加了 1
。对于 ThreadPool.QueueUserWorkItem
它增加了 3。
并对 Task.Run(() => {...})
进行了相同的测试。令人惊讶的是,线程数增加了 4
,有时甚至增加了 5
。不幸的是,我无法理解原因。
这里是完整的测试代码:
static void Main(string[] args)
{
new Thread(() =>
{
while (true)
{
Thread.Sleep(500);
Console.WriteLine(System.Diagnostics.Process.GetCurrentProcess().Threads.Count);
}
}).Start();
//Task.Run(() =>
//{
// Thread.Sleep(5000);
//}); // thread count is 12
//new TaskFactory().StartNew(() =>
//{
// Thread.Sleep(5000);
//}); // thread count is 12
//ThreadPool.QueueUserWorkItem((onj) =>
//{
// Thread.Sleep(5000);
//}); // thread count is 9
//new Thread(() =>
//{
// Thread.Sleep(5000);
//}).Start(); // thread count is 7
Console.ReadLine();
}
我的问题是,为什么 运行 new Task 会增加 4 或 5 个线程数?为什么线程池的排队工作项会使线程数增加 3?
线程池使用 complicated mechanism 来确定将有多少个线程 运行。
当您通过调用 QueueUserItem
或创建 Task
将工作排队到线程池时,线程池会使用默认的初始线程数进行初始化,通常为四个。