Call Connection.Close / Dispose in the finalizer

I always called Connection.Close in the finally block, however today I found out that you should not do this :

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

So, understanding that deleting the SqlCommand object does not delete or close the connection object associated with it, will the following (simplified code below) delete the command and connection object at the same time? and do I really need to call Connection.Dispose if I'm 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
+3
source share
2 answers

No, you do not need to explicitly call Close if you are using a block Using. Here is how I wrote 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, the call Closedoes not close the connection. ADO.NET uses a connection pool, so calling Close simply returns a connection to the pool. This does not physically close the connection.

+5
source

What you do is beautiful. Finalizers are different from the last blocks. Check out http://www.switchonthecode.com/tutorials/csharp-tutorial-object-finalizers for a discussion of which finalizers.

+1
source

All Articles