使用非受控資源的型別必須實作 IDisposable.Dispose() 精確釋放系統資源。.NET 環境規定釋放資源程式碼的責任在型別使用者,而非型別或系統。因此,任何時候使用有 Dispose() 的型別,你就有責任呼叫 Dispose() 釋放資源。最佳確保結構是 using 陳述式或 try/finally 區塊。
所有包含非受控資源的型別應實作 IDisposable。若忘記妥善處理,它們會被動建立解構函式。忘記處理時,非記憶體資源在稍後解構函式確切呼叫時才釋放,導致物件在記憶體停留更久,應用程式因系統資源佔用過多而變慢。
C# 設計者精確釋放資源是常見任務,添加關鍵字使其簡單。假設寫了下列程式碼:
public void ExecuteCommand(string connString, string commandString)
{
SqlConnection myConnection = new SqlConnection(connString);
SqlCommand MySQLCommand = new SqlCommand(commandString, myConnection);
myConnection.Open();
MySQLCommand.ExecuteNonQuery();
}
兩可處理物件 SqlConnection、SqlCommand 未妥善釋放,將留在記憶體直到解構函式被呼叫(兩者繼承自 System.ComponentModel.Component)。
解決方法是在用完後呼叫 Dispose:
MySQLCommand.Dispose(); myConnection.Dispose();
這很好,除非 SQL 命令執行時拋出例外,此時 Dispose() 永不會成功。using 陳述式確保 Dispose() 被呼叫。物件配置在 using 內時,編譯器將其置入 try/finally:
public void ExecuteCommand(string connString, string commandString)
{
using (SqlConnection myConnection = new SqlConnection(connString))
{
using (SqlCommand MySQLCommand = new SqlCommand(commandString, myConnection))
{
myConnection.Open();
MySQLCommand.ExecuteNonQuery();
}
}
}