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

- **ID:** `dotnet/ef-core-connection-timeout`
- **领域:** dotnet
- **类别:** resource_error
- **错误码:** `0x80131904`
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

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

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| net6.0 | active | — | — |
| net7.0 | active | — | — |
| net8.0 | active | — | — |
| net9.0 | active | — | — |

## 解决方案

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.
   ```

## 无效尝试

- **Increasing Max Pool Size in connection string to a very high value (e.g., 1000)** — This only masks the underlying issue of connection leaks; the pool will eventually exhaust again under higher load. (85% 失败率)
- **Restarting the application or IIS pool to clear connections** — Temporary fix; connections will leak again once the app runs, as the root cause (missing Dispose) persists. (90% 失败率)
- **Disabling connection pooling entirely (Pooling=false)** — Severely impacts performance by creating a new connection for every request, leading to slower response times and potential socket exhaustion. (95% 失败率)
