请看下面的代码:
Public Class Form1
Private _ConString As String
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim objDR As SqlDataReader
Dim objCommand As SqlCommand
Dim objCon As SqlConnection
Dim id As Integer
Try
_ConString = ConfigurationManager.ConnectionStrings("TestConnection").ToString
objCon = New SqlConnection(_ConString)
objCommand = New SqlCommand("SELECT * FROM Person")
objCommand.Connection = objCon
objCon.Open()
objDR = objCommand.ExecuteReader(ConnectionState.Closed)
Do While objDR.Read
id = objDR("URN")
Loop
objDR.Close() 'line 16
Catch ex As Exception
throw
Finally
End Try
End Sub
End Class
连接对象在第 16 行关闭。请看下面的代码:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim objDR As SqlDataReader
Dim objCommand As SqlCommand
Dim objCon As SqlConnection
Dim id As Integer
Try
_ConString = ConfigurationManager.ConnectionStrings("TestConnection").ToString
objCon = New SqlConnection(_ConString)
objCommand = New SqlCommand("SELECT * FROM Person")
objCommand.Connection = objCon
objCon.Open()
Using objCon
Using objCommand
objDR = objCommand.ExecuteReader()
Do While objDR.Read
id = objDR("URN")
Loop
End Using
End Using
objDR.Close() 'line 16
Catch ex As Exception
throw
Finally
End Try
End Sub
我注意到在这两种情况下,连接对象和命令对象在关闭后仍然具有状态(通过按照代码示例 1 关闭数据读取器或按照代码示例 2 移出 Using 语句)。这可能是内存泄漏的根源吗?