「連接超時」與「命令執行超時」是 ADO.NET 開發中最常見的兩類超時問題,成因不同、配置位置不同、解決策略也不同。本文徹底釐清兩者區別,提供從配置到代碼的完整優化方案。
| 維度 | 連接超時 (Connection Timeout) | 命令超時 (Command Timeout) |
|---|---|---|
| 發生階段 | 建立物理連接時 | 命令發送後等待結果時 |
| 默認值 | 15 秒 (SqlClient) | 30 秒 (SqlCommand.CommandTimeout) |
| 配置位置 | 連接字符串 Connect Timeout=30 | 代碼 cmd.CommandTimeout = 60 |
| 典型報錯 | "Timeout expired. The timeout period elapsed prior to completion of the operation..." | "Execution Timeout Expired. The timeout period elapsed prior to completion of the operation..." |
| 常見原因 | 網絡不通、防火牆、實例名錯誤、連接池耗盡 | 查詢慢、鎖阻塞、缺少索引、大數據量處理 |
telnet server 1433、ping server。Data Source=192.168.1.100,1433;Initial Catalog=MyDB;User Id=sa;Password=xxx;
Connect Timeout=30;Pooling=true;Max Pool Size=200;
using 或 finally 關閉連接;監控性能計數器 NumberOfPooledConnections。await conn.OpenAsync() 避免阻塞 UI 線程。cmd.CommandTimeout = 120(秒),0 表示無限等待(慎用)。SELECT *,只取所需列。ROW_NUMBER() 或 Keyset Pagination。SqlBulkCopy / Table-Valued Parameters。DataReader 流式讀取,避免 DataTable.Load 佔用內存。await cmd.ExecuteReaderAsync()、ExecuteNonQueryAsync(),配合 CancellationToken 實現可取消查詢。web.config 中 <httpRuntime executionTimeout="110" />(秒)控制請求總超時,需大於命令超時。IIS 請求限制 <system.webServer><security><requestFiltering><requestLimits maxAllowedContentLength="..."/></requestFiltering></security></system.webServer> 也可能間接影響。
MiniProfiler、Glimpse 或 EF Core Logging 定位慢查詢。區分連接與命令超時,從網絡、配置、SQL、架構多維度優化,才能徹底解決 ADO.NET 超時難題。