In c# mongodb driver, there are both synchronous and asynchronous methods available as shown below?
_mongoCollection.InsertOneAsync(entity);
_mongoCollection.Insert(entity);
I believe, in majority of cases, the amount of work done asynchronously in data access layer is very less. So I am awaiting the database calls immediately as follows:
await _mongoCollection.InsertOneAsync(entity);
await _mongoCollection.DeleteOneAsync(query);
await _mongoCollection.Find(query).ToListAsync();
Now my question is: As i am awaiting the db calls immediately, I am not seeing any use of async methods here. So, should I use async methods? (or) Should i use synchronous methods?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With