I have multiple threads accessing the same database (with same connection string). Each thread:
- creates it's own SqlConnection instance using the same connection string
uses code below to open it's own connection instance whenever it needs one
try { wasOpened = connection.State == ConnectionState.Open; if (connection.State == ConnectionState.Closed) { connection.Open(); } } catch (Exception ex) { throw new Exception(string.Format("Connection to data source {0} can not be established! Reason: {1} - complete stack {2}", connection.Database, ex.Message, ex.StackTrace == null ? "NULL" : ex.StackTrace.ToString())); }
We have tested this code on 2 servers so far, and one server sometimes throws an exception in SqlConnection.Open method. Here is the exception message we get from catch block:
Connection to data source xyz can not be established! Reason: Invalid operation. The connection is closed. - complete stack
at System.Data.SqlClient.SqlConnection.GetOpenConnection()
at System.Data.SqlClient.SqlConnection.get_Parser()
at System.Data.SqlClient.SqlConnection.Open()
Inspecting SqlConnection.GetOpenConnection method shows that innerConnection
is null:
internal SqlInternalConnection GetOpenConnection()
{
SqlInternalConnection innerConnection = this.InnerConnection as SqlInternalConnection;
if (innerConnection == null)
{
throw ADP.ClosedConnectionError();
}
return innerConnection;
}
It stays unclear to me: why does connection pool sometimes give me severed connection (innerConnection == null)?
Edit #1: there are no static properties in code - we ARE always closing connection when appropriate, wasOpened is used in our Close method and means: if connection was already opened when our Open is called, just leave it open on Close, otherwise close it. However, this is not related to problem described in this question (innerConnection == null).
Edit #2: Server: SQL Server 2008 R2, Windows Server 2003. Client: Windows Server 2003 (code runs within SSIS package custom component). Connection string: Data Source=server_name;Initial Catalog=db_name;Integrated Security=SSPI;Application Name=app_name
using-statement
. Is something static here? – Jus