I have several threads accessing the same database (with the same connection string). Each thread:
- creates its own instance of SqlConnection using the same connection string
uses the code below to open his own connection instance when he needs
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 the SqlConnection.Open method. Here is the exception message that we get from the catch block:
Unable to connect to xyz data source! Reason: Invalid operation. The connection is closed. - full stack
in System.Data.SqlClient.SqlConnection.GetOpenConnection ()
in System.Data.SqlClient.SqlConnection.get_Parser ()
in System.Data.SqlClient.SqlConnection.Open ()
Checking the 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 remains unclear to me: why does the connection pool sometimes give me a disconnected connection (innerConnection == null)?
Change # 1 : there are no static properties in the code - we always close the connection, if necessary, wasOpened is used in our Close method and means: if the connection was already open when Open was called, just leave it open when closing, otherwise close it. However, this is not related to the problem described in this question (innerConnection == null).
Edit # 2 : Server: SQL Server 2008 R2, Windows Server 2003. Client: Windows Server 2003 (code is executed in the custom component of the SSIS package). Connection string: Data Source=server_name;Initial Catalog=db_name;Integrated Security=SSPI;Application Name=app_name
source share