2013-08-05 107 views
3

我有一個C#應用程序,通過C#ThreadPool執行多線程插入到MongoDB中。但是,我已經得到了TimeoutException: Timeout waiting for a MongoConnection。我正在使用MongoServer.RequestStart方法,它應該將連接釋放回MongoClient連接池。釋放連接回到MongoDB連接池

此外,線程池至少有4個線程,最多8個線程,而Mongo連接池默認有100個連接,所以我不應該沒有連接。

那麼,爲什麼我會得到這個錯誤?

下面是傳遞給線程池的方法。 _client是一個MongoClient實例變量。

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);  
     } 
    } 

這就是我如何將它傳遞給線程池。

private void SendWorkToThreadPool(string collectionName, BinaryPacketDocument[] documents, int batchSize) { 
     if (documents.Length != 0) { 
      ThreadPool.QueueUserWorkItem(state => _inserter.BatchInsert(collectionName, documents, batchSize)); 
     } 
    } 

回答

1

我意識到我的線程池實際上並不限於8個線程。如果將0作爲ThreadPool.SetMax/Min線程的參數之一傳遞,它將無法設置max(但不是顯式地)。