Consider this code (Yes its ugly but it should also work):
try
{
// Test the connection to a database that does not exist yet...
using (SqlConnection c = new SqlConnection("Data Source=localhost;Initial Catalog=test;Integrated Security=True"))
{
c.Open();
} // Dispose calls Close()
}
catch
{
//... will fail with an exception
}
// Creating the database...
using (SqlConnection c = new SqlConnection("Data Source=localhost;Integrated Security=True"))
{
c.Open();
SqlCommand cmd = new SqlCommand("CREATE DATABASE test", c);
cmd.ExecuteNonQuery();
}
using (SqlConnection c = new SqlConnection("Data Source=localhost;Initial Catalog=test;Integrated Security=True"))
{
c.Open(); // Failes with the same exception even though the database have been created in between.
// ...
}
If I remove the inital check that throws the first exception it will work and it will not throw the second exception. Why do I get this behaviour? Its almost as if the first exception is being remembered/cached for this connectionstring until the second time. But the database has been created (Ive verified that of course) in between so it shouldnt...
Update:
The problem was connection-pooling as ValdV suggested. Ive changed the code above to the following and it now works:
try
{
using (SqlConnection c = new SqlConnection(cstr))
{
c.Open();
}
}
catch
{
SqlConnection.ClearAllPools(); // clear all pooled connections
}
Somehow it didnt work just clearing the failed connection, I had to clear all...