0

请看下面的代码:

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 语句)。这可能是内存泄漏的根源吗?

4

2 回答 2

0

你应该做这样的事情......

Using Conn as new SqlConnection(_ConString)
 Dim cmd as New SqlCommand(Conn, "Select * FROM Person");
   id = Convert.ToInt32(cmd.ExecuteScalar())
End Using

如果必须,请尝试将其包装起来,但前提是您要以某种方式处理它。(一个简单的“投掷”不会处理任何事情。)

您还使用 DataReader(迭代,仅转发)数据访问组件来获取单个值。您可能希望使用ExecuteScalar () 来简化该代码。

除此之外,不要将“已处置”与“已关闭”混淆。.NET 框架为您管理垃圾收集。如果您想处理连接和命令对象,请在它们上调用 .Dispose() (但 Using 会为您处理这个!!!)

于 2012-11-21T20:19:28.100 回答
0

回复:这可能是内存泄漏的根源吗? 不,不应该。

还有,这个:

            objDR = objCommand.ExecuteReader()
            Do While objDR.Read
                id = objDR("URN")
            Loop

看起来很糟糕,因为它遍历所有行并覆盖 id 值。最后一行设置以 ID 中的值结束。您正在从一组多行中获取一个结果。如果您只想要max(URN)from Person,您可以编写命令来返回该结果。

于 2012-11-21T20:37:30.887 回答