title: Releasing Connections back to MongoDB Connection Pool
body: <p>I have a C# application that performs multi-threaded inserts via the C# ThreadPool into MongoDB. However, I have been getting a <code>TimeoutException: Timeout waiting for a MongoConnection</code>. I'm using the MongoServer.RequestStart method, which should be releasing the connection back into the MongoClient connection pool. </p>
  
  <p>Also, the threadpool has a minimum of 4 threads and maximum of 8, while the Mongo connection pool has a default of 100 connections, so I shouldn't be running out of connections.</p>
  
  <p>So why am I getting this error? </p>
  
  <p>Here's the method which is passed into the threadpool. <code>_client</code> is a MongoClient instance variable.</p>
  
  <pre><code>public void BatchInsert(string collectionName, BinaryPacketDocument[] documents, int batchSize) {
          MongoServer server = _client.GetServer();
          MongoDatabase database = server.GetDatabase(_databaseName);
          using (server.RequestStart(database)) {
              MongoCollection collection = database.GetCollection(collectionName);
              collection.InsertBatch(documents);
              StatisticsManager.GetCounter("logs").Add(batchSize);    
          }
      }
  </code></pre>
  
  <p>And here's how I pass it into the threadpool.</p>
  
  <pre><code>private void SendWorkToThreadPool(string collectionName, BinaryPacketDocument[] documents, int batchSize) {
          if (documents.Length != 0) {
              ThreadPool.QueueUserWorkItem(state =&gt; _inserter.BatchInsert(collectionName, documents, batchSize)); 
          }
      }
  </code></pre>