了解MongoDB新C#驱动程序中的更改(异步和等待)

Sex*_*yMF 10 c# mongodb mongodb-csharp-2.0 mongodb-.net-driver

新的C#驱动程序完全是Async,在我的理解中,在n层架构中扭曲了一些旧设计模式,例如DAL.

在我的Mongo DALs中我用来做:

public T Insert(T entity){
     _collection.Insert(entity);
     return entity;
}
Run Code Online (Sandbox Code Playgroud)

这样我就能得到坚持ObjectId.

今天,一切都是Async等InsertOneAsync.
如何将Insert方法现在将返回entityInsertOneAsync会做些什么呢?你能举个例子吗?

mne*_*syn 15

理解async/ 的基础是有帮助的,await因为它有点漏洞,并且有很多陷阱.

基本上,您有两种选择:

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

    // Insert:
    collection.InsertOneAsync(user).Wait();
    
    // FindAll:
    var first = collection.Find(p => true).ToListAsync().Result.FirstOrDefault();
    
    Run Code Online (Sandbox Code Playgroud)
  • 在代码库中转到异步.不幸的是,执行异步非常具有"传染性",所以要么将所有内容转换为异步,要么不转换.小心,混合同步和异步错误将导致死锁.使用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;
    
    Run Code Online (Sandbox Code Playgroud)