使用“使用”时最后关闭SqlConnection
我想关闭最后的SqlConnection,因为使用并没有真正关闭它,连接池变满了。 但是我没有意识到什么是正确的方法,因为conn对象在finally部分中不再可用。
try { using (var conn = new SqlConnection(_dbconnstr)) { //... } } catch (Exception ex) { //... } finally { conn.Close //?!?!?!?!??? }
using (var conn = new SqlConnection(_dbconnstr)) { //code }
被透露给:
SqlConnection conn = new SqlConnection(_dbconnstr); try { //code } finally { conn.Dispose(); }
所以你应该处理错误,但你可以忘记关闭连接。
您不需要在finally
块中关闭conn
。 using
块将处理为您关闭连接。 (事实上,在这种情况下,你可能根本不需要try...finally
除非你有其他资源需要在finally
处理。)
using
块将转换为以下内容:
var conn = new SqlConnection(/*...*/); try { // ... } finally { if (conn != null) ((IDisposable)conn).Dispose(); }
将在finally
块中调用SqlConnection
对象的Dispose
方法,并且Dispose
方法继续为您调用Close
。
退出using块会在对象上调用.Dispose()
,因为SqlConnection
将关闭连接和任何打开的资源。
所以try
, finally
阻止是不需要的。
根据我的理解,连接对象的Dispose()方法将关闭Connection。 您不需要显式调用Connection.Close。
你Using
关闭连接的方式是好的。 也许您可能忘记关闭一些DataReader了?
AFAIK,以下使用声明:
using (var conn = new SqlConnection(_dbconnstr)) { }
相当于:
SqlConnection conn; try { //`using` scope operations are executed here conn = new SqlConnection(_dbconnstr)); } catch { //exceptions are bubbled throw; } finally { //Dispose is always called conn.Dispose(); }
- generics与inheritance(当不涉及集合类时)
- Environment.GetEnvironmentVariable将找不到变量值
- .net核心中的CPU使用率(至少在Windows上)
- 使用Label控件在c#winform中创建循环选框文本
- FileStream.BeginWrite优于FileStream.Write?
- Marshal.PtrToStringUni()vs new String()?
- 数据库未启动但SQL Server已准备好进行连接时出现SqlException
- 如何插入具有自动增量编号作为主键的新记录?
- PInvoke和EntryPointNotFoundException