简体   繁体   中英

closing connections within a using block

On reading lots of code, I find that a given Connection object, which implements IDisposable , is is manually closed within a using statement. I see this when I see code related to MySQL.

It's not needed to be explicitly closed. Why would the developer close it manually?

using(cnn)
{
    //code is here
    cnn.close();
}

Is this a good/helpful measure?

显式地关闭using块是重复,误导和冗余的,所以对我来说,这是一件坏事

It depends on the connection. Many close themselves in the Dispose method. SQLConnection for example closes itself in the Dispose.

I think it's reasonable to suppose that an object implementing IDisposable should clean up its own resources and not require the close. Now it might not close as quickly as you might want, so you would manually close them yourself, but then you wouldn't use the using syntax.

It's not needed, as IDbConnection is specified as closing on Dispose().

(Strictly, it's specified as releasing resources on Dispose(), but that amounts to calling close. If some sort of db connection didn't take any resources then it wouldn't have to, but then that wouldn't be an issue anyway).

It can however be useful to call close prior to that, as the sooner connection objects are closed the better, but the using can catch early escape from the block (whether by an exception or, eg returning early in certain cases).

As a rule, it's good to keep the using blocks nice and tight, which removes the advantage, but there can be exceptions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM