title: C#, Dapper, SQL Server and Connection Pooling
body: <p>I've written some code to write some data to SQL Server, using Dapper.  I don't need to wait for this write to complete before continuing other work, so want to use Task.Run() to make this asynchronous.</p>
  
  <p>I have (using) statements for calling this in the rest of my system:</p>
  
  <pre><code> using (IDataAccess ida = new DAL())
          {
              ida.WriteMessageToDB(id, routingKey, msgBody);
          }
  </code></pre>
  
  <p>My DAL will automatically check the dbConnection.State when the using statement is ran, and attempt a simple fix if it's closed.  This works just fine for any non-async/TPL select calls.</p>
  
  <p>However, when I throw a load of writes at the same time, the Task.Run() code was falling over as the connection was closed for some of them - essentially I think the parallel nature of the code meant the state was being closed by other tasks.</p>
  
  <p>I 'fixed' this by doing a check to open the Connection.State within the Task.Run() code, and this appears to have 'solved' the problem.  Like so:</p>
  
  <pre><code>Task.Run(() =&gt;
              {
                  if (dbConnection.State == ConnectionState.Closed)
                  {
                      dbConnection.Open();
                  }
  
                  if (dbConnection.State == ConnectionState.Open)
                  {
                      *Dapper SQL String and Execute Commands*
                  }
              });
  </code></pre>
  
  <p>When I run <code>SELECT * FROM sys.dm_exec_connections</code> from SSMS after this, I see a lot more connections.  To be expected?</p>
  
  <p>Now as I understand it:</p>
  
  <ul>
  <li>Dapper doesn't deal with connection pooling</li>
  <li>SQL Server should automatically deal with connection pooling?</li>
  </ul>
  
  <p>Is there anything wrong with this solution?  Or a better way of doing it?  I'd like to use connection pooling for obvious reasons, and as painlessly as possible.</p>
  
  <p>Thanks in advance.</p>