Does End Using close an open SQL Connection

2019-01-06 16:33发布

问题:

If I wrap a SQLConnection in a Using, should I close it or does the end using handle it?

using cn as new system.data.sqlclient.sqlconnection()
    cn.open
    '{do a bunch of other stuff with commands and datareaders here}
    cn.close 'Do I need this?
end using 

回答1:

Exiting a using block calls .Dispose() on the object in question (cn in your example) which for a SqlConnection will close the connection and any open resources.



回答2:

More precisely calling Dispose or Close will mark the underlying physical connection as "Not in use" - but doesn't really close it. A "Not in use" connection that isn't yet physically closed is thus available for pooling. Therefore - calling Dispose would return a connection to the connection pool.



回答3:

According to MSDN you don't need the close statement.

"The following example creates a SqlConnection, opens it, displays some of its properties. The connection is automatically closed at the end of the using block." -- http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.close.aspx



回答4:

While the SQL's Dispose method does close the connection (eventually according to darin) you should leave the call to Close in there. The reason is that you would be relying on the underlying implementation of Dispose to call close. Also seeing an Open without a Close is like seeing a New without a Delete for those of us that have programmed in unmanaged languages. It's a code smell for me.



回答5:

"A Using block behaves like a Try...Finally construction in which the Try block uses the resources and the Finally block disposes of them. Because of this, the Using block guarantees disposal of the resources, no matter how you exit the block. This is true even in the case of an unhandled exception, except for a StackOverflowException."
https://msdn.microsoft.com/en-us/library/htd05whh.aspx



回答6:

using is just a shorthand to try/finally. this is equivilent code to what you posted

Try
    SqlConnection cn as new system.data.sqlclient.sqlconnection()
    cn.open
    '{do a bunch of other stuff with commands and datareaders here}
    cn.close 'Do I need this?
Finally
    cn.Dispose()
End Try

Dispose is supposed to take care of all resource cleanup, in the case of connections it will close it.