在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方法,那么系统就会报错。
博客介绍了在C#里,实现了IDisposable接口的类如SqlConnection和SqlCommand,使用完后调用Dispose方法可尽快释放内存。推荐使用using或try/finally语句,还给出了示例代码,并提醒使用using语句时,若类未实现Dispose方法会报错。
187

被折叠的 条评论
为什么被折叠?



