title: SqlConnection not being disposed when using async
body: <p>I have a project that has a Sql-Server database back end and Dapper as an ORM. I am attempting to use Dapper's <code>QueryAsync()</code> method to get some data.  Not only that, but the call to my repo is coming from inside several tasks that are called with a <code>Task.WhenAll</code> (That is to say, each task involves getting data from that repo, so each task awaits my repo's method that wraps the <code>QueryAsync()</code> call).  </p>
  
  <p>The problem is that my SqlConnections never close even though I am using a <code>using</code> block.  As a result, I have 100+ open connections to my database, and eventually start getting "max pool size reached" exceptions.  The thing is, when I switch to just <code>Query()</code> instead of <code>QueryAsync()</code>, it works fine, but I'd like to be able to do this asynchronously.</p>
  
  <p>Here's a code example.  I tried to mimic the structure of the actual applicatoin as best as I could, which is why it looks more complex than it has to be.</p>
  
  <p>Interface:</p>
  
  <pre><code>public interface IFooRepository&lt;T&gt; where T: FooBase
  {
      Task&lt;IEnumerable&lt;T&gt;&gt; Select(string account, DateTime? effectiveDate = null);
  }
  </code></pre>
  
  <p>Implementation:</p>
  
  <pre><code>public class FooRepository : RepositoryBase, IFooRepository&lt;SpecialFoo&gt;
  {
      private readonly IWebApiClientRepository _accountRepository;
  
      public FooRepository(IWebApiClientRepository repo)
      {
          _accountRepository = repo;
      }
      public async Task&lt;IEnumerable&lt;FuturePosition&gt;&gt; Select(string code, DateTime? effectiveDate = null)
      {
          effectiveDate = effectiveDate ?? DateTime.Today.Date;
          var referenceData =  await _accountRepository.GetCrossRefferenceData(code, effectiveDate.Value);
          using (var connection = new SqlConnection("iamaconnectionstring")
          {
              connection.Open();
              try
              {
                  var res = await connection.QueryAsync&lt;FuturePosition&gt;(SqlQueryVariable + "AND t.code = @code;",
                      new
                      {
                          effectiveDate = effectiveDate.Value,
                          code = referenceData.Code
                      });
  
                  foreach (var item in res)
                  {
                      item.PropFromReference = referenceData.PropFromReference;
                  }
                  return res;
              }
              catch (Exception e)
              {
                  //log 
                  throw;
              }
              finally
              {
                  connection.Close();
              }
          }
      }
  }
  </code></pre>
  
  <p>So now with the calling code, there are 2 layers.  I'll start with the outer one.  I think this is where the problem is.  There are comments in the below.</p>
  
  <p>Populator:</p>
  
  <pre><code>public class Populator : PopulatorBase
  {
      private IAccountRepository _acctRepository;
      public override async Task&lt;IEnumerable&lt;PopulationResult&gt;&gt; ProcessAccount(DateTime? popDate = null)
      {
          //My attempt at throttling the async calls
          //I was hoping this would force a max of 10 simultaneous connections.
          //It did not work.
          SemaphoreSlim ss = new SemaphoreSlim(10,10);
          var accountsToProcess = _acctRepository.GetAllAccountsToProcess();
          var accountNumbers = accountsToProcess.SelectMany(a =&gt; a.accountNumbers).ToList();
  
          List&lt;Task&lt;ProcessResult&gt;&gt; trackedTasks = new List&lt;Task&lt;ProcessResult&gt;&gt;();
          foreach (var item in accountNumbers)
          {
              await ss.WaitAsync();
              trackedTasks.Add(ProcessAccount(item.AccountCode, popDate ?? DateTime.Today));
              ss.Release();
          }
          //my gut tells me the issue is because of these tasks
          var results = await Task.WhenAll(trackedTasks);
          return results;
      }
  
      private async Task&lt;ProcessResult&gt;ProcessAccount(string accountCode, DateTime? popDate)
      {
          var createdItems = await _itemCreator.MakeExceptions(popDate, accountCode);
          return Populate(accountCode, createdItems);
      }
  }
  </code></pre>
  
  <p>ItemCreator:</p>
  
  <pre><code>public class ItemCreator : ItemCreatorBase
  {
      private readonly IFooRepository&lt;FuturePosition&gt; _fooRepository;
      private readonly IBarRepository&lt;FuturePosition&gt; _barRepository;
  
      public RussellGlobeOpFutureExceptionCreator() )
      {
          //standard constructor stuff
      }
      public async Task&lt;ItemCreationResult&gt; MakeItems(DateTime? effectiveDate, string account)
      {
          DateTime reconDate = effectiveDate ?? DateTime.Today.Date;
  
          //this uses the repository I outlined above
          var foos = await _fooRepository.Select(account, effectiveDate);
  
          //this repository uses a rest client, I doubt it's the problem
          var bars = await _barRepository.Select(account, effectiveDate);
  
          //just trying to make this example less lengthy
          var foobars = MakeFoobars(foos, bars);
          var result = new ItemCreationResult { EffectiveDate = effectiveDate, Items = foobars };
          return result;
      }
  }
  </code></pre>
  
  <p>As far as what I've tried:</p>
  
  <ul>
  <li>Throttling with a SemaphoreSlim</li>
  <li>No throttling</li>
  <li>Using <code>connection.OpenAnync()</code> in the repo</li>
  <li>including/excluding a finally block (should be irrelevant with <code>using</code>)</li>
  </ul>
  
  <p>Its worthwhile to know that the <code>foreach</code> loop in the populator runs around 500 times.  Essentially, there's a list of 500 accounts.  For each one, it needs to do a long running <code>populate</code> task which involves pulling data from my Foo repo. </p>
  
  <p>I honestly have no idea.  I think it might have to do with awaiting my async db call from each task inside that list of tasks in the populator.  Any insight into this issue would be super helpful.</p>