MongoCollection returns 数据同步但不异步

MongoCollection returns data sync but not async

我一直在尝试将 sync 逻辑转换为 async 并意识到我的 async await 模式不起作用。

我已经更改了这段代码:

var filter = Builders<SmartAgentProperty>.Filter.Where(smartAgent => smartAgent.UserMail==userMail);
var results = await SmartAgentsCollection.FindAsync(filter);
return results.ToList();

对此:

var filter = Builders<SmartAgentProperty>.Filter.Where(smartAgent => smartAgent.UserMail == userMail);
var results = SmartAgentsCollection.Find(smartAgent => smartAgent.UserMail == userMail).ToEnumerable();
return Task.FromResult(results);

sync 版本完美运行。

async 版本挂起,不会抛出任何异常。

听起来,这是一个非常奇怪的错误。

我认为我可能做错了,但似乎相同的模式在我的代码的其他地方也有效,所以我正在寻求帮助。

根据 Craig 的评论,问题已解决!

一个。我用错了(Task.FromResult 而不是实际的异步实现)

b。我错过了 configureAwait(false)

c。应该使用 Find(filter).ToListAsync() 而不是 FindAsync(filter).ToEnumerable()

修复后的代码如下:

return await _smartAgentsCollection
      .Find(smartAgent => smartAgent.UserMail == userMail)
      .ToListAsync().ConfigureAwait(false);