Sqlhelper.ExecuteReader关闭connection的方式

 刚下载了Microsoft.ApplicationBlocks.Data看了看,了解了Sqlhelper.ExecuteReader返回的datareader是如何关闭的。
首先在SqlHelper类中有个枚举类型的变量SqlConnectionOwnership,它有两个值InternalExternal; 用来指示connection的关闭方式。当传给ExecuteReader的参数为External时(由外部调用者传入connection),connection由调用者关闭,否则cmd.ExecuteReader(CommandBehavior.CloseConnection),即在调用command的ExecuteReader时设置为关闭datareader的时候同时自动关闭connection.
相关代码如下:

       /// <summary>
        
/// This enum is used to indicate whether the connection was provided by the caller, or created by SqlHelper, so that
        
/// we can set the appropriate CommandBehavior when calling ExecuteReader()
        
/// </summary>

         private   enum  SqlConnectionOwnership    
        
{
            
/// <summary>Connection is owned and managed by SqlHelper</summary>
            Internal, 
            
/// <summary>Connection is owned and managed by the caller</summary>
            External
        }

//////////////////

        
private   static  SqlDataReader ExecuteReader(SqlConnection connection, SqlTransaction transaction, CommandType commandType,  string  commandText, SqlParameter[] commandParameters, SqlConnectionOwnership connectionOwnership)
        
{    
            
if( connection == null ) throw new ArgumentNullException( "connection" );
            
bool mustCloseConnection = false;
            
// Create a command and prepare it for execution
            SqlCommand cmd = new SqlCommand();
            
try
            
{
                PrepareCommand(cmd, connection, transaction, commandType, commandText, commandParameters, 
out mustCloseConnection );
                  
// Create a reader
                SqlDataReader dataReader;

                
// Call ExecuteReader with the appropriate Command Behavior
                if (connectionOwnership == SqlConnectionOwnership.External)
                
{
                    dataReader 
= cmd.ExecuteReader();
                }

                
else
                
{
                    dataReader 
= cmd.ExecuteReader(CommandBehavior.CloseConnection);
                }

                
bool canClear = true;
                
foreach(SqlParameter commandParameter in cmd.Parameters)
                
{
                    
if (commandParameter.Direction != ParameterDirection.Input)
                        canClear 
= false;
                }

            
                
if (canClear)
                
{
                    cmd.Parameters.Clear();
                }


                
return dataReader;
            }

            
catch
            
{
                
if( mustCloseConnection )
                    connection.Close();
                
throw;
            }

        }


你可能感兴趣的:(Connection)