【问题标题】:MongoCollection returns data sync but not asyncMongoCollection 返回数据同步但不异步
【发布时间】:2016-05-25 07:09:49
【问题描述】:

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

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

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

【问题讨论】:

  • 看起来您复制了两次相同的代码。为什么在那个 sn-p 中需要“过滤器”?
  • 哎呀,更正了 sn-p。我已经添加了过滤器,因为我过去遇到过问题,过滤器是问题
  • 您可以尝试将异步版本更改为:return await SmartAgentsCollection.Find(filter).ToListAsync();
  • 另外,请记住,您可能需要在异步调用结束时添加 ConfigureAwait(false),否则您可能会陷入死锁,具体取决于您使用的应用程序类型。 return await SmartAgentsCollection.Find(filter).ToListAsync().ConfigureAwait(false);
  • 试过ToListAsync()没有成功。

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


【解决方案1】:

所以根据 Craig 的评论,问题解决了!

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

b.我错过了configureAwait(false)

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

修复后的代码如下:

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

【讨论】:

    猜你喜欢
    • 2019-09-30
    • 2015-08-24
    • 2021-02-23
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    相关资源
    最近更新 更多