开发者

Calling Connection.Close/Dispose in finaliser

开发者 https://www.devze.com 2023-03-11 16:37 出处:网络
I\'ve always called Connection.Close in the finally block, however I learned today you aren\'t supposed to do that:

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
    sqlCm开发者_开发知识库d.Connection.Close()
End Using


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.


What you are doing is fine. Finalizers are different from finally blocks. Check out http://www.switchonthecode.com/tutorials/csharp-tutorial-object-finalizers for a discussion of what finalizers are.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号