在c#中,有些类是实现了IDisposable接口的,应此具有方法Dispose(),例如SqlConnection和SqlCommand。在使用这些类的时候,一旦用完了这些类最好是能调用这些类的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();
}
}
}
public void ExecuteCommand( string connString,
string commandString )
{
SqlConnection myConnection = null;
SqlCommand mySqlCommand = null;
try {
myConnection = new SqlConnection( connString );
mySqlCommand = new SqlCommand( commandString,
myConnection );
myConnection.Open();
mySqlCommand.ExecuteNonQuery();
}
finally
{
if ( mySqlCommand != null )
mySqlCommand.Dispose();
if ( myConnection != null )
myConnection.Dispose();
}
}
在使用using语句是要注意如果using语句中的类没有实现Dispose方法,那么系统就会报错。