gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:02:59 24 4
gpt4 key购买 nike

新的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com