Calling Dispose() vs when an object goes out scope/method finishes

前端 未结 6 739
情深已故
情深已故 2020-12-30 05:58

I have a method, which has a try/catch/finaly block inside. Within the try block, I declare SqlDataReader as follows:

SqlDataReader         


        
6条回答
  •  太阳男子
    2020-12-30 06:26

    You should use a using {...} block to wrap your IDisposable objects in - the Dispose() method (which for SqlDataReader passes off to the Close() method) will be called when the using block ends. If you do not use using, the object will not be automatically disposed when it goes out of scope - it will be up to the object finalizer, if it has one, to get rid of resources when it is garbage collected

    using (SqlDataReader aReader = aCommand.ExecuteReader())
    {
        // ... do stuff
    }   // aReader.Dispose() called here
    

提交回复
热议问题