B
BobRoyAce
I have a function, shown below, that returns a SqlDataReader. The
function creates a SqlConnection that it uses to create the
SqlDataReader. If I run this function over and over, does it cause a
"memory leak" since the SqlConnections aren't being disposed of? When
a generated SqlDataReader goes away, does that automatically free the
memory for the associated SqlConnection? For example, let's say I have
the following Sub:
Private Sub DoSomething()
Dim sSQL As String = "SELECT * FROM MyTable"
Dim rdr As SqlClient.SqlDataReader = GetDataReaderForSQL(sSQL)
' Do something with rdr...
End Sub
What should I do, at the end of the DoSomething Sub above, to make
sure I don't create a memory leak?
Public Function GetDataReaderForSQL(ByVal sSQL As String) As
SqlClient.SqlDataReader
Dim cnn As New
SqlClient.SqlConnection(My.Settings.GRPConnectionString.ToString)
cnn.Open()
Dim cmd As New SqlClient.SqlCommand(sSQL, cnn)
Dim rdr As SqlClient.SqlDataReader
Try
rdr =
cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
Catch ex As Exception
MessageBox.Show("GetDataReaderForSQL" & vbCrLf & vbCrLf &
ex.Message & vbCrLf & ex.StackTrace, "GRP", _
MessageBoxButtons.OK, MessageBoxIcon.Warning)
rdr = Nothing
End Try
Return rdr
End Function ' GetDataReaderForSQL
function creates a SqlConnection that it uses to create the
SqlDataReader. If I run this function over and over, does it cause a
"memory leak" since the SqlConnections aren't being disposed of? When
a generated SqlDataReader goes away, does that automatically free the
memory for the associated SqlConnection? For example, let's say I have
the following Sub:
Private Sub DoSomething()
Dim sSQL As String = "SELECT * FROM MyTable"
Dim rdr As SqlClient.SqlDataReader = GetDataReaderForSQL(sSQL)
' Do something with rdr...
End Sub
What should I do, at the end of the DoSomething Sub above, to make
sure I don't create a memory leak?
Public Function GetDataReaderForSQL(ByVal sSQL As String) As
SqlClient.SqlDataReader
Dim cnn As New
SqlClient.SqlConnection(My.Settings.GRPConnectionString.ToString)
cnn.Open()
Dim cmd As New SqlClient.SqlCommand(sSQL, cnn)
Dim rdr As SqlClient.SqlDataReader
Try
rdr =
cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)
Catch ex As Exception
MessageBox.Show("GetDataReaderForSQL" & vbCrLf & vbCrLf &
ex.Message & vbCrLf & ex.StackTrace, "GRP", _
MessageBoxButtons.OK, MessageBoxIcon.Warning)
rdr = Nothing
End Try
Return rdr
End Function ' GetDataReaderForSQL