可以使用 Using 块保证系统在代码退出该块时释放资源。如果正在使用消耗大量内存或其他组件也需要使用的系统资源时,这样处理十分有用。
代码完成数据库连接时释放数据库连接
-
确保在源文件的开始包含该数据库连接的适当 Imports 语句(本例中为 System.Data.SqlClient)。
-
创建具有 Using 和 End Using 语句的 Using 块。在块中放入处理数据库连接的代码。
-
声明连接并创建其实例作为 Using 语句的一部分。
' Insert the following line at the beginning of your source file.
Imports System.Data.SqlClient
Public Sub AccessSql(ByVal s As String)
Using sqc As New System.Data.SqlClient.SqlConnection(s)
MsgBox("Connected with string """ & sqc.ConnectionString & """")
End Using
End Sub
无论退出块的方式如何(包括未处理异常的情况),系统都会释放该资源。
注意:不能从 Using 块外部访问 sqc,这是因为其范围只限于该块。
对系统资源(如文件句柄或 COM 包装)可以使用同样的方法。如果要确保退出 Using 块后其他组件还能使用资源,则可使用 Using 块。
请参见