closing connections within a using block

自作多情 提交于 2019-12-11 06:56:10

问题


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.



来源:https://stackoverflow.com/questions/4068705/closing-connections-within-a-using-block

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!