1

How do i add data to MOngo Db synchronously ? Is it a good idea to use asynchronously method to add user data in server ?

I have user registration form, when user click on create button it should add user data to Mongo db collection. But in Mongo db site they have explained asynchronous methods to insert data using c# driver. But i want to insert it synchronously. 1. User click on create button 2. Insert data to Mongo DB 3. Show success message to user.

here in step 2, if it is asynchronous, it will go to step3 without completing step 2 correct ? So user will get success message before completing the request. That is not a good idea right ?

Is it a good logic that adding user info using asynchronous method?

Why c# mongo db drivers providing only asynchronous option to insert\find data?

D.Rosado
  • 5,634
  • 3
  • 36
  • 56
Gayathri
  • 85
  • 2
  • 11
  • If you use the await it will lock the main thread until it ends. – brduca May 13 '15 at 13:23
  • Read my question, i think it can help : [Insert new document using InsertOneAsync (.NET Driver 2.0)][1] [1]: http://stackoverflow.com/questions/29599412/insert-new-document-using-insertoneasync-net-driver-2-0 – Hana May 13 '15 at 13:39

2 Answers2

1

Is it a good idea to use asynchronous method to add user data in server?

Yes, it is, since it allows the server to process other requests while it's waiting for I/O to complete, i.e. you allow the same number of threads to handle more requests.

Also, forcing synchrony using .Result or .Wait() is dangerous because you will run into deadlocks if you don't do it right.

Is it a good logic that adding user info using asynchronous method?

asynchronous only means that the server can use the thread for something else in-between; this is largely transparent, i.e. your code doesn't have to care much. For practical purposes, simply call await InsertOneAsync(...) or whatever MongoDB driver method you're calling.

Why c# mongo db drivers providing only asynchronous option to insert\find data?

Async is a pretty 'infectious' feature: to make efficient use of the async feature, all your code must be able to deal with it.

mnemosyn
  • 45,391
  • 6
  • 76
  • 82
0

You can easily turn the asynchronous calls into synchronous calls using the await keyword:

var results = await collection.Find(conditions).ToListAsync();

Why does the C# driver implement all operations as asynchronous by default? Because it is easier to use an asynchronous API synchronously than the other way around.

Also, in general using an asynchronous API leads to more responsive and faster applications in general because it makes it easy for the developer to write an application which performs many simultaneous operations. Instead of awaiting the results immediately, store the ongoing async operations in Tasks and resolve them when you need them. For more information read the article "Asynchronous Programming with Async and Await" on MSDN.

Philipp
  • 67,764
  • 9
  • 118
  • 153