I have a simple helper function that looks up data in a SQL Server database and returns a dataset.
This function is used in lot of different places in my web application.
For the most part, it works great. However when there are a lot of concurrent users all connected at the same time, I will occasionally get errors like this:
DBUtilities.getDataSet: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
When this happens, I don't see any errors in the database server event log, only the web server event logs.
After reading about garbage collection and disposing of objects, I'm starting to think that maybe the database connections are not getting closed or disposed of properly.
I was wondering, would there be a way to place this code in some type of wrapper that could help dispose of the database objects properly?
Here is the function I am referring too:
Public Overloads Function getDataSet(ByVal commandText As String, Optional ByVal tableName As String = "") As DataSet
Dim ds As New DataSet
Dim conn As New SqlConnection(myConnStr)
Try
Dim cmd As New SqlCommand(commandText, conn)
cmd.CommandTimeout = 30
cmd.CommandType = CommandType.Text
Dim da As New SqlDataAdapter
da.SelectCommand = cmd
conn.Open()
If String.IsNullOrEmpty(tableName) Then
da.Fill(ds)
Else
da.Fill(ds, tableName)
End If
Catch ex As Exception
Throw New Exception("AppDataMethods.getDataSet: " & ex.Message & ", cmdText = " & commandText)
Finally
conn.Close()
conn = Nothing
End Try
Return ds
End Function