title: SQL Server connection pool doesn't detect closed connections?
body: <p>For years, I've experienced very weird problems on all my web applications that connect to a SQL server.</p>
  
  <p>The problem is that if something happens to the database server (server restart or other problem), de web app stops working from that point on, even if the database server is alive and well afterwards.</p>
  
  <p>What happens is that every ADO.NET operation (ExecuteNonQuery, CreateReader, BeginTransaction, ...) fails with a <strong>InvalidOperationException</strong>: "<em>Invalid operation. The connection is closed</em>". It seems that a call to <strong>SqlConnection.Open()</strong> retrieves a connection from the application pool which is... closed! </p>
  
  <p>According to the documentation, the connection pool should automatically remove severed connections from the connection pool, but apparantly a closed connection isn't regarded as "severed", so the call to <strong>SqlConnection.Open()</strong> happily returns a closed connection, assuming it is open, without checking this.</p>
  
  <p>My current workaround is to check for the state of the connection right after opening it:</p>
  
  <pre><code>using (SqlConnection connection = new SqlConnection( connectionString ))
  {
     connection.Open();
  
     if (connection.State != ConnectionState.Open)
     {
        SqlConnection.ClearAllPools();
  
        connection.Open();
     }
  
     // ...
  }
  </code></pre>
  
  <p>This workaround seems to work for now, but I don't feel comfortable doing this. </p>
  
  <p>So my questions are:</p>
  
  <ol>
  <li>Why does <strong>SqlConnection.Open()</strong> return closed connections from the connection pool?</li>
  <li>Is my workaround valid?</li>
  <li>Is there a better way to handle this?</li>
  </ol>