c# - 了解 MongoDB 新 C# 驱动程序的变化(Async 和 Await)

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

新的 C# 驱动程序完全是异步的,并且在我的理解中有点扭曲了旧的设计模式,例如 n 层架构中的 DAL。

在我使用的 Mongo DAL 中:

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

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

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

最佳答案

了解 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 .使用异步有很多优点,因为您的代码可以在 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;
    

关于c# - 了解 MongoDB 新 C# 驱动程序的变化(Async 和 Await),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30091922/

相关文章:

c# - 运行时可浏览(假)?

c# - 我需要添加什么才能使用 "using System.Timers;"?

javascript - 使用 React.js 插入 MongoDB 文档

c# - MongoDB C# 驱动程序 MongoCredential 对象

c# - 无法在 MongoDb 集合查询中将 ObjectId 反序列化为 String

c# - ASP :RequiredFieldValidator validation based on conditions

c# - 如何覆盖 List<T> 包含

python - 如何在 Python 中创建一组在 Mongodb 中唯一的字段组合

c# - 如何测试 MongoDB 文档中的字符串字段不为空?

c# - MongoDb c#驱动程序按字段值在数组中查找项目