Should I use synchronous or asynchronous methods of c# mongodb driver? Should I use synchronous or asynchronous methods of c# mongodb driver? mongodb mongodb

Should I use synchronous or asynchronous methods of c# mongodb driver?


I think the prior answers are missing a major point of asynchrony; namely that when you use the async methods**, you free up the thread you're on while (most of) the I/O operation completes, and it is available for use elsewhere in your app; e.g. servicing other requests.

Let's suppose the Mongo database is on another server. Even with a quick network and quick Mongo instance, that's still perhaps 5ms per command, which on a 2GHz CPU is 10 million clock cycles. While you're not going to get all of those to use on running your code, due to various overheads, you will get still get an advantage if you have an app that can use the additional threads productively.

So if your app is for instance a website, API, or UI, I would use the async methods. If it's a single thread console app, you probably won't gain any of the above benefit.

--

** This assumes the Mongo async method are truly async, and not just wrappers for the sync methods.


that depends on if you have any use of result in next statement or not.

for e.g.

void async myMethod(){   var result = funcAsync();   // do some additional work..   var data = await result;   .   . }

above is scenario where you should use async await.

Now let assume if you have method;

void async myMethod(){   var result = await funcAsync(); // here result is required before any other logic ahead   .   .   . }

here you really don't need to use async await, but what if in near future your system changed and you need to add additional code in between, then you might need to change method signatures and corresponding location where that method is called.

So this is totally depends on the requirement.


It really depends on what are your requirements.

From the code you've posted I can guess that you don't need an asynchronous call but it may come in handy with the last call _mongoCollection.Find(...).ToListAsync()

Asynchronous calls ( IMHO ) should be used only when you have some independent/complex logic. In example that you showed I think you can only await the last call making it :

_mongoCollection.Insert(entity);_mongoCollection.Find(query).ToListAsync();

This way you can simply do some extra logic while awaiting ToListAsync() :

_mongoCollection.Insert(entity);Task<List<object>> _task = _mongoCollection.Find(query).ToListAsync();// my complex logic/calculations and stuff await _task;

Being 100% honest I don't see any other reason to use asynchronous calls.

My opiniion is that from your example, usage of asynchronous call is just useless.