Dot-Net-3.5
為什麼要呼叫 SqlClient.SqlDataReader Close() 方法呢?
SqlClient.SqlDataReader 是否是 .NET 託管對象?為什麼我們必須呼叫 Close() 方法顯式關閉打開的連接?這樣一個對象的範圍不應該自動關閉嗎?垃圾收集器不應該清理它嗎?
請幫助我了解這裡的最佳做法是什麼。
我在這裡看到了一個相關的問題,它進一步說明了我在使用 Web 應用程序時遇到的問題。問題是我們的連接用完了。詳細的錯誤在這裡:
Exception: System.InvalidOperationException Message: 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. Source: System.Data at System.Data.SqlClient.SqlConnectionPoolManager.GetPooledConnection(SqlConnectionString options, Boolean& isInTransaction) at System.Data.SqlClient.SqlConnection.Open()為了解決這個問題,我必須明確關閉所有 SQLDataReader 對象。
我正在使用 .NET Framework 3.5
當然,它會在超出範圍時被收集(如果它們沒有其他引用)。當它被收集時,它將通過它的 Dispose() 方法關閉。然而,你永遠不知道 GC 什麼時候會釋放東西;如果你不關閉你的讀者,你很快就會用完與數據庫的可用連接。
延伸閱讀
- O’Reilly 的ADO.NET 連接池解釋
- Microsoft 的使用 DataReader 檢索數據對 DataReader進行了總體概述。
~ 威廉·萊利-蘭德