在finaliser中调用Connection.Close/Dispose

Mr *_*ubs 3 .net connection ado.net garbage-collection database-connection

我总是在finally块中调用Connection.Close,但是我今天学到了你不应该这样做:

不要在类的Finalize方法中对Connection,DataReader或任何其他托管对象调用Close或Dispose.在终结器中,您应该只释放您的类直接拥有的非托管资源.如果您的类不拥有任何非托管资源,请不要在类定义中包含Finalize方法

因此,了解到处理SqlCommand对象不会释放或关闭分配给它的连接对象,下面的(下面的简化代码)是否会同时处理命令和连接对象?如果我确定我总是调用Connection.Close,我真的需要调用Connection.Dispose吗?

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
Run Code Online (Sandbox Code Playgroud)

Dar*_*rov 5

不,如果您正在使用Using块,则无需显式调用Close .这是我写它的方式:

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
Run Code Online (Sandbox Code Playgroud)

同时调用Close不会关闭连接.ADO.NET使用连接池,因此调用Close只会返回到池的连接.它没有物理关闭连接.