【问题标题】:Understanding the changes in MongoDB new C# driver (Async and Await)了解 MongoDB 新 C# 驱动程序(Async 和 Await)的变化
【发布时间】:2015-05-07 04:26:22
【问题描述】:

新的 C# 驱动程序完全是异步的,据我了解,它稍微扭曲了旧的设计模式,例如 n 层架构中的 DAL。

在我的 Mongo DAL 中,我曾经这样做过:

public T Insert(T entity){
     _collection.Insert(entity);
     return entity;
}

这样我可以得到持久化的ObjectId

今天,一切都是异步的,例如InsertOneAsync
InsertOneAsync 完成时,Insert 方法现在将如何返回entity?可以举个例子吗?

【问题讨论】:

    标签: c# mongodb mongodb-.net-driver mongodb-csharp-2.0


    【解决方案1】:

    了解async / await 的基础知识会很有帮助,因为它是一个有些漏洞的抽象并且有许多陷阱。

    基本上,您有两个选择:

    • 保持同步。在这种情况下,在异步调用中分别使用.Result.Wait() 是安全的,例如像

      // Insert:
      collection.InsertOneAsync(user).Wait();
      
      // FindAll:
      var first = collection.Find(p => true).ToListAsync().Result.FirstOrDefault();
      
    • 在您的代码库中使用异步。不幸的是,异步执行非常“具有传染性”,因此您要么将几乎所有内容都转换为异步,要么不进行。小心,mixing sync and async incorrectly will lead to deadlocks。使用 async 有很多优点,因为您的代码可以在 MongoDB 仍在工作时继续运行,例如

      // FindAll:
      var task = collection.Find(p => true).ToListAsync();
      // ...do something else that takes time, be it CPU or I/O bound
      // in parallel to the running request. If there's nothing else to 
      // do, you just freed up a thread that can be used to serve another 
      // customer...
      // once you need the results from mongo:
      var list = await task;
      

    【讨论】:

    • 同步使用 MongoDB 就像用经典的 ASP 应用程序调用 SQL 数据库?它会锁定整个网站直到通话结束吗?
    • 你需要添加一些特定的东西来使await task 行工作吗?它一直在大喊await 需要在async 上完成一些事情。但当然是这样,因为.ToListAsync() 就在那里。知道可能是什么问题吗? @mnemosyn
    • @mcpDESIGNS: await 只能在声明为 async 的方法中使用。
    • 我通常将 Mongo 与 Node/mongoose 一起使用,所以在 C# 世界中对我来说似乎很奇怪。我尝试将async Task FooAsync(IMongoCollection<BsonDocument> collection) 作为一种方法并且有效。谢谢。我想将它们相互链接是下一个让我感到困惑的部分......哈哈
    • Async/await 应该非常接近节点所做的......无论如何,我建议你退后一步,从一个不使用异步库的简单异步控制台应用程序开始...... . 另外,IMongoCollection<BsonDocument> 对我来说看起来不太好(为什么不强类型?)但这与原来的问题相差太远了......
    【解决方案2】:

    就我而言:当我收到此错误时:

    源 IQueryable 未实现 IAsyncEnumerable。只有来源 实现 IAsyncEnumerable 可用于实体框架 异步操作。

    我已经为 mongodb 实现了 async where 函数,如下所示。

    public async Task<IEnumerable<TEntity>> Where(Expression<Func<TEntity, bool>> expression = null)
    {
         return await context.GetCollection<TEntity>(typeof(TEntity).Name, expression).Result.ToListAsync();
    }
    

    【讨论】:

      猜你喜欢
      • 2012-12-20
      • 2020-03-25
      • 1970-01-01
      • 1970-01-01
      • 2020-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多