Understanding the changes in MongoDB new C# driver (Async and Await)

陌路散爱 提交于 2020-01-12 05:09:07

问题


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.

In my Mongo DALs I use to do:

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

This way I can get the persisted ObjectId.

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?


回答1:


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:

  • Remain synchronous. In this case, it's safe to use .Result and .Wait() on the async calls, respectively, e.g. something like

    // Insert:
    collection.InsertOneAsync(user).Wait();
    
    // FindAll:
    var first = collection.Find(p => true).ToListAsync().Result.FirstOrDefault();
    
  • 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;
    


来源:https://stackoverflow.com/questions/30091922/understanding-the-changes-in-mongodb-new-c-sharp-driver-async-and-await

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!