Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Connection.Close/Dispose in finaliser

I've always called Connection.Close in the finally block, however I learned today you aren't supposed to do that:

Do not call Close or Dispose on a Connection, a DataReader, or any other managed object in the Finalize method of your class. In a finalizer, you should only release unmanaged resources that your class owns directly. If your class does not own any unmanaged resources, do not include a Finalize method in your class definition

So with the understanding that disposing of the SqlCommand object does not dispose or close the connection object assigned to it, would the following (simplified code below) dispose of the command and connection object at the same time? and do I really need to call Connection.Dispose if I make sure I always call Connection.Close?

Using cmd As New NpgsqlCommand(String.Empty, new connection())
    cmd.CommandText = "some sql command here"
    sqlCmd.Connection.Open()
    ...create and fill data table
    sqlCmd.Connection.Close()
End Using
like image 619
Mr Shoubs Avatar asked Apr 18 '26 02:04

Mr Shoubs


1 Answers

No, you don't need to call Close explicitly if you are using a Using block. Here's how I would write it:

Using conn As New SqlConnection("SOME CONNECTION STRING")
    Using cmd = conn.CreateCommand()
        conn.Open()
        cmd.CommandText = "some sql command here"

        ' ... create and fill data table
    End Using
End Using

Also calling Close doesn't close the connection. ADO.NET uses a connection pool so calling Close simply returns the connection to the pool. It doesn't physically close the connection.

like image 156
Darin Dimitrov Avatar answered Apr 20 '26 14:04

Darin Dimitrov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!