MongoCollection返回数据同步但不返回异步

时间:2016-05-25 07:09:49

标签: c# mongodb asynchronous mongodb-.net-driver data-access-layer

我一直试图将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版本已挂起,并且不会抛出任何异常。

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

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

1 个答案:

答案 0 :(得分:0)

所以根据克雷格的评论,问题解决了!

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

湾我错过了configureAwait(false)

℃。应该使用Find(filter).ToListAsync()代替FindAsync(filter).ToEnumerable()

修复后的代码:

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