We have a helper class that we use to call stored procs on SQL Server. The helper function looks like this:
using (sqlCon = new SqlConnection(connectionString))
{
// Create database command object
sqlCmd = sqlCon.CreateCommand();
sqlCmd.CommandTimeout = commandTimeout;
// Set command text AND command type
sqlCmd.CommandText = procedureName;
sqlCmd.CommandType = CommandType.StoredProcedure;
// Set command parameters
if (paramCollection != null)
{
foreach (DatabaseParameter dbParam in paramCollection)
{
SqlParameter sqlParam = sqlCmd.Parameters.Add(dbParam.ParameterName, dbParam.ParameterType);
sqlParam.Direction = dbParam.ParameterDirection;
sqlParam.Value = dbParam.ParameterValue;
if (dbParam.ParameterSize != -1)
sqlParam.Size = dbParam.ParameterSize;
if (dbParam.ParamPrecision != -1)
sqlParam.Precision = (byte)dbParam.ParamPrecision;
if (dbParam.ParamScale != -1)
sqlParam.Scale = (byte)dbParam.ParamScale;
}
}
try
{
sqlCon.Open();
}
catch
{
SqlConnection.ClearAllPools();
sqlCon.Open();
}
// Prepare command
sqlCmd.Prepare();
// Execute the statement
sqlCmd.ExecuteNonQuery();
if (sqlCmd.Parameters.Contains("@Result"))
return sqlCmd.Parameters["@Result"].Value;
else
return "Completed";
}
So we are making sure connections are closed properly.
The app is a multi threaded service and all the threads calls this method quite regularly. We do lock (thisobject) {} sections around the code that calls the above helper method to prevent the threads from stealing each others connections.
The connection.Open is inside a try catch with the ClearAllpools to clear broken connections.
However, we intermittently through the day get the following list of errors at random intervals.
The connection’s current state is connecting.
or
The connection’s current state is open.
The errors happen about once in every several thousand times the code is called, so it’s quite hard to troubleshoot. Has anybody seen anything similar or ideas on what could be wrong?
I’ve run across these types of errors when dealing with a multi-threaded app, even when using a
lock. After endless hours of debugging, I never found the problem and ended up trying to re-connect several times before giving up. To date, I haven’t seen the error arise again.