I'm running a multi-threaded operation that fetches data from a SQL Server database using SqlConnection
and Parallel.ForEach()
and following is happening:
SqlConnection
in a using
statement so that the connection is properly disposed.SqlException
wrapped in an AggregateException
after running successfully for some time ("A network-related or instance-specific error occurred while establishing a connection to SQL Server..")using(...)
)I'm at a loss on how to instruct .NET to close-out those connections. I thought that that happened auto-magically when the SqlConnection
is disposed.
The issue seems to be with how the connection is opened. I'm using this constructor
public SqlConnection(string connectionString, SqlCredential credential)
It seems that ADO creates a new connection pool, even when connectionString
is the same and credential
encapsulates the same credentials. My guess is that ADO somehow can't relate the credential to prior calls (maybe it would work if I was using the same credential object by using reference equality? In my case, I create a new SqlCredential with each call).
Because of a new pool is created each time, the number of TCP connections balloons. I think this also makes sense when the connection pool is turned off. Likely some of the socket or TCP settings are kicking-in here (keep alives?) and the OS is keeping the connections open to respect those settings.