Skip to content
标签
欢迎扫码关注公众号

C# Task 中的最大线程数

今天线上发现了点问题,猜测是创建线程失败导致的,所以写了段代码测试下最大线程数。

csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace MaxThreadCountTest
{
    class Program
    {
        private static Object lockObject = new Object();

        static void Main(string[] args)
        {
            int threadCount = 0;
            for (int i = 0; i < 5000; i++)
            {
                Task task = Task.Factory.StartNew(() => {
                    lock (lockObject)
                    {
                        threadCount++;
                        Console.WriteLine("当前线程 ID:" + Thread.CurrentThread.ManagedThreadId + " (总线程:" + threadCount + "个)");
                    }
                    Thread.Sleep(Timeout.Infinite);
                });
            }

            while (Console.ReadLine().ToLower() != "exit")
            {
                Console.WriteLine("当前线程数为:" + threadCount);
            }
        }
    }
}

结果最后打印的是

当前线程 ID:1030 (总线程:1023 个)

说明默认的最大线程数是 1023,之后的线程创建也没有失败,只是进入了等待状态,待前面的线程结束后,才会真正启动并运行。

2023-07-12 追记

在 .NET Framework 和 .NET Core 中,默认线程池的大小取决于操作系统和运行时的版本。在 Windows 上,对于 .NET Framework 4.x,默认线程池的最大线程数为 1023。而在 .NET Core 或较新的 .NET 版本中,默认线程池的最大线程数则为 CPU 核心数的两倍。

要注意的是,默认线程池大小并不是固定的,它可以根据应用程序的需求进行动态调整。当线程池中的线程耗尽并且需要创建更多线程来处理任务时,线程池会自动增加线程数量。相反,如果线程池中的线程空闲一段时间,并且没有新的任务到达,线程池会缩减线程数量以节省资源。

如果你想自定义线程池的大小,可以使用 ThreadPool.SetMaxThreadsThreadPool.SetMinThreads 方法来设置。例如,你可以使用以下代码将最大线程数设置为 1000:

csharp
ThreadPool.SetMaxThreads(1000, 1000);

需要注意的是,直接设置线程池的最大线程数可能会对系统资源产生影响,因此应根据应用程序的需求和系统的性能来进行合理的配置。

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.