【发布时间】:2014-12-01 09:43:29
【问题描述】:
在我的程序执行的某个点,它们通过使用
创建了超过 2 个连接件Con.Close()
只有一个连接被关闭,其余的进入睡眠状态。如何关闭所有打开的连接,包括休眠连接。
【问题讨论】:
在我的程序执行的某个点,它们通过使用
创建了超过 2 个连接件Con.Close()
只有一个连接被关闭,其余的进入睡眠状态。如何关闭所有打开的连接,包括休眠连接。
【问题讨论】:
SqlConnection 类实现IDisposable。所以你直接使用Dispose() 方法。有效的做法是使用using 块
using(SqlConnection connection = new SqlConnection())
{
// Do something
}// Here it will automatically call Dispose()
您仍然需要打开连接,但不需要关闭它,因为正如我提到的,Dispose() 方法将处理 using 块末尾的对象。
为确保连接始终关闭,请打开里面的连接 一个 using 块,如下面的代码片段所示。这样做可以确保 当代码退出块时,连接会自动关闭。
Using connection As New SqlConnection(connectionString)
connection.Open()
'Do work here; connection closed on following line.'
End Using
【讨论】:
Using,我不需要使用Con.Open() 来打开连接和Con.Close() 来关闭连接?你能在vb.net中解释清楚吗