了解MongoDB新C#驱动程序中的更改(异步和等待) [英] Understanding the changes in MongoDB new C# driver (Async and Await)

查看:86
本文介绍了了解MongoDB新C#驱动程序中的更改(异步和等待)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的C#驱动程序完全是异步的,在我的理解中,它有点扭曲了旧的设计模式,例如n层体系结构中的DAL.

The new C# driver is totally Async and in my understanding twists a little bit the old design patterns such as DAL in n-tier architecture.

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

In my Mongo DALs I use to do:

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

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

This way I can get the persisted ObjectId.

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

Today, everything is Async such as InsertOneAsync.
How would Insert method will now return the entity when the InsertOneAsync will be done? Can you show an example?

推荐答案

了解async/await的基础非常有帮助,因为它是一个有点漏水的抽象并且有很多陷阱.

It's helpful to understand the basics of async / await because it's a somewhat leaky abstraction and has a number of pitfalls.

基本上,您有两个选择:

Essentially, you have two options:

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

// Insert:
collection.InsertOneAsync(user).Wait();

// FindAll:
var first = collection.Find(p => true).ToListAsync().Result.FirstOrDefault();

  • 在您的代码库中进行异步处理.不幸的是,异步执行是相当传染性的",因此您可以将几乎所有内容都转换为异步,也可以不转换为异步.小心,错误地将同步和异步混合会导致死锁.使用异步有很多优点,因为您的代码可以在MongoDB仍在工作时继续运行,例如.

  • Go async in your code base. Doing it async is quite 'infectious', unfortunately, so either you convert pretty much everything to async, or not. Careful, mixing sync and async incorrectly will lead to deadlocks. Using async has a number of advantages, because your code can continue to run while MongoDB is still working, e.g.

    // 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新C#驱动程序中的更改(异步和等待)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆