closing connections within a using block

2019-07-29 10:42发布

问题:

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?

回答1:

Explicitly closing in a using block is duplication, misleading and redundant so for me, is a bad thing.



回答2:

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



回答3:

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, e.g. 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.



回答4:

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.