EffectiveC#15--使用using和try/finally来做资源清理

1.任何时候你在使用一个有Dispose()方法的类型时,你就有责任来调用Dispose()方法来释放资源。

  最好的方法来保证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(); }
catch
{} finally { if ( mySqlCommand != null ) //注意这里判断对象是否为null是很重要的一些封装了COM的对象,有些时候的释放是隐式的,当你再释放一些空对象时会出现异常 mySqlCommand.Dispose(); if ( myConnection != null ) myConnection.Dispose(); } }

sqlconnection它还有close(),Dispose方法会释放更多的资源,它还会告诉GC,这个对象已经不再须要析构了

2.使用或包含非托管资源的类型必须实现IDisposable接口的Dispose()方法来精确的释放系统资源。

原文地址:https://www.cnblogs.com/tiantianle/p/4890246.html