C# - 运行 40 Foreach 迭代需要 5 秒

C# - Running 40 Foreach Iterations takes 5 seconds

下面这段代码需要 5 秒进行 40 次迭代。我不认为这与 MongoDb 有任何关系,因为过滤器应该立即构建并且调用应该只在这里进行,而不是等待。如果您在这里看到每次迭代需要超过 1000 秒的任何内容,请告诉我:

//There are 40 categories
foreach (var category in categories)
{
var filter = Builders<BsonDocument>.Filter.In("CurrentOfficeId", officesIds)
            & Builders<BsonDocument>.Filter.Eq("CategoryId", category.Id);

if (userId > 0) filter &= Builders<BsonDocument>.Filter.Eq("SubmittedById", userId);

pendingCallsForItemCountPerCatArray[numberOfCatBeingIterated] = mongoItemsCollection
                                                                    .Find(filter)
                                                                    .CountAsync();
}

编辑:请注意,我试图在上一个呼叫完成之前进行每个呼叫。否则代码如下:

callResult[numberOfCatBeingIterated] = await mongoItemsCollection

编辑 2:我确认调用正在生成一个 Task<long>,而不是一个长的。我还确认注释掉调用会将迭代时间降低到 0 秒,我们知道这一点,但我只是确认一下。

可能是因为您总是使用 .Find(filter) 遍历 mongoItemsCollection 吗?

每当代码 "taking long time" 执行时 - 这是一个很好的理由来查看 mongoDB 中的内容:-)。

  1. 在分析器模式下设置mongo

db.setProfilingLevel(2,20)

  1. 然后检查那里发生了什么

db.system.profile.find().limit(100).sort( { ts : -1 } ).pretty()

  1. 完成后

db.setProfilingLevel(0)

因为一次有 40 个调用 125 ms/per 调用看起来很不错(假设您在每个查询期间都有一个锁)