为什么在运行新任务时与线程启动不同,线程数增加了4或5?

问题描述 投票:2回答:1

我试图借助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();
}

我的问题是,为什么运行新的Task会使线程数增加4或5?为什么将线程池的工作项目排队,会使线程数增加3?]

已更新:我从动作主体中删除了Thread.Slepp调用,但是每个示例的线程数都没有改变。

c# .net task-parallel-library threadpool
1个回答
1
投票
线程池使用complicated mechanism确定将运行多少个线程。

当您通过调用QueueUserItem或创建Task将工作排队到线程池中时,线程池将使用默认的初始线程数(通常为四个)进行初始化。

© www.soinside.com 2019 - 2024. All rights reserved.