Does End Using close an open SQL Connection

前端 未结 6 1493
礼貌的吻别
礼貌的吻别 2020-11-29 05:53

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
           


        
相关标签:
6条回答
  • 2020-11-29 06:04

    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.

    0 讨论(0)
  • 2020-11-29 06:05

    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.

    0 讨论(0)
  • 2020-11-29 06:06

    "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

    0 讨论(0)
  • 2020-11-29 06:07

    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

    0 讨论(0)
  • 2020-11-29 06:07

    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.

    0 讨论(0)
  • 2020-11-29 06:20

    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.

    0 讨论(0)
提交回复
热议问题