Listing 1: Using a SqlDataReader to Return Rows from a Query and Close the Connection.
Dim sngLeak as Single
Try ' Trap exceptions during this routine.
' Capture the number of pooled connections.
sngLeak = pcPooledConnections.NextValue
' Create a new DataReader.
Dim dr as SqlDataReader
Dim i as Integer
Dim strAuID as String
lblConnections.Text = "0"
[BEGIN CALLOUT A]
For i = 1 To 110
Dim cn As New SqlConnection("server=.;" _
& "integrated security=true;max pool size=10")
Dim cmd As New SqlCommand("SELECT TOP 5 au_id" _
& " FROM pubs..authors", cn)
lblConnections.Text = i.ToString ' Show connection count.
lblRtn.Text = (i.ToString)
cn.Open() ' DataReader requires a pre-opened connection.
[END CALLOUT A]
[BEGIN CALLOUT B]
If cbCBCmdBehavior.Checked Then
dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)
Else
dr = cmd.ExecuteReader()
End If
[END CALLOUT B]
[BEGIN CALLOUT C]
If cbUseGrid.Checked Then
DataGrid1.DataSource = dr
DataGrid1.DataBind()
Else
DataGrid1.DataSource = Nothing
While dr.Read
strAuID = dr.GetValue(0).ToString
End While
End If
[END CALLOUT C]
[BEGIN CALLOUT D]
If cbCloseConnection.Checked Then
cn.Close() ' This should be enough; it closes the connection.
Else
' Don't manually close the connection.
' This should cause a leak if the connection isn't closed elsewhere.
End If
If cbCloseDataReader.Checked Then
dr.Close()
Else
' Don't manually close the connection.
' This might cause a leak.
End If
lblPooledConnections.Text = pcPooledConnections.NextValue.ToString
lblUserConnections.Text = pcUserConnections.NextValue.ToString
Next i
lblRtn.Text &= "
" & "All 110 operations complete."
[END CALLOUT D]
[BEGIN CALLOUT E]
Catch exI As System.InvalidOperationException
lblRtn.Text &= "
" & "Could not open connection: " _
& exI.Message
Catch ex As Exception ' Unexpected exceptions
lblRtn.Text &= "
" & (ex.ToString)
Finally
' Calculate the number of additional pooled connections created.
' This number should be 0.
lblLeaks.Text = (pcPooledConnections.NextValue - sngLeak).ToString
lblRtn.Text &= ("
" & "Done")
End Try
End Sub
[END CALLOUT E]