0x80131904 dotnet resource_error ai_generated true

Microsoft.Data.SqlClient.SqlException (0x80131904): 连接超时已过期。在从池中获取连接之前超时时间已过。这可能是因为所有池化连接都在使用中且达到了最大池大小。

Microsoft.Data.SqlClient.SqlException (0x80131904): Connection Timeout Expired. The timeout period elapsed prior to obtaining a connection from the pool. This may have occurred because all pooled connections were in use and max pool size was reached.

ID: dotnet/ef-core-connection-timeout

其他格式: JSON · Markdown 中文 · English
85%修复率
85%置信度
1证据数
2023-06-15首次发现

版本兼容性

版本状态引入弃用备注
net6.0 active
net7.0 active
net8.0 active
net9.0 active

根因分析

连接池耗尽,因为连接未正确关闭/释放,或者池大小对于并发负载来说太小。

English

The connection pool is exhausted because connections are not being closed/disposed properly, or the pool size is too small for the concurrent load.

generic

官方文档

https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-pooling

解决方案

  1. Ensure all DbContext instances are properly disposed by using 'using' blocks or dependency injection with AddDbContext and scoped lifetime. Example: 'using (var context = new MyDbContext()) { ... }' or services.AddDbContext<MyDbContext>(options => options.UseSqlServer(connectionString), ServiceLifetime.Scoped)
  2. Increase connection pool size and add connection leak detection. Set 'Max Pool Size=200; Connection Lifetime=300' in the connection string, and enable 'Pooling=True' with 'Load Balance Timeout=30'. Also monitor with 'SELECT * FROM sys.dm_exec_sessions' to identify orphaned connections.
  3. Use 'using var connection = new SqlConnection(connectionString);' and wrap in try-finally or use 'await using' for async operations. For EF Core, ensure 'context.Database.CloseConnection()' is called in long-running operations.

无效尝试

常见但无效的做法:

  1. Increasing Max Pool Size in connection string to a very high value (e.g., 1000) 85% 失败

    This only masks the underlying issue of connection leaks; the pool will eventually exhaust again under higher load.

  2. Restarting the application or IIS pool to clear connections 90% 失败

    Temporary fix; connections will leak again once the app runs, as the root cause (missing Dispose) persists.

  3. Disabling connection pooling entirely (Pooling=false) 95% 失败

    Severely impacts performance by creating a new connection for every request, leading to slower response times and potential socket exhaustion.