Will putting a “using” statement around a DataReader close it?

后端 未结 4 1454
栀梦
栀梦 2020-12-18 17:52

I usually write my DataReader code like this:

try
{
    dr = cmd.ExecuteReader(CommandBehavior.SingleResult);
    while (dr.Read())
    {
               


        
4条回答
  •  庸人自扰
    2020-12-18 18:20

    Yes. using calls Dispose. Calling Dispose on SqlDataReader closes it.

    This is psuedo-code of SqlDataReader gleaned from Reflector:

        public void Dispose()
        {
            this.Close();
        }
    
        public override void Close()
        {
            if( !IsClosed )
                CloseInternal(true);
        }
    
        private void CloseInternal(bool closeReader)
        {
            try
            {
                // Do some stuff to close the reader itself
            }
            catch(Exception ex)
            {
                this.Connection.Abort();
                throw;
            }
    
            if( this.Connection != null && CommandBehavior.CloseConnection == true )
            {
                this.Connection.Close();
            }
        }
    

提交回复
热议问题