Is there a way to use MongoDB C # driver synchronously

I have a 2 layer C # project. The first is the data layer, which connects to mongodb and sends collections to the web service layer. The problem is that I couldn't find in the new methods not async

for drivers (i.e. Synchronous).

Is there a way to use synchronous methods with the C # driver for mongodb version 2.0?

Hint: is it possible to run mongodb shell functions using C #?

+3


source to share


2 answers


EDIT: In driver v2.2, they add synchronous versions for all async operations, which are synchronous almost all the way down. If you cannot use async-await for some reason, this is the next best option.


You have to use the async

operations as a driver async

, and the operations are essentially asynchronous (mostly I / O, usually to a remote server).

But, if you have to keep things in sync, you have 3 options, ordered with the least recommended:



  • Continue using the old (v1.x) version of the driver with the synchronous API.
  • Use a newer driver, but with a deprecated API ( client.GetServer

    ). It requires a different nuget package (called Legacy) and has both API types.
  • Use operations async

    and block them with Task.Result

    or Task.Wait

    .

The older version is preferred because it uses synchronous I / O, which is usually better than consuming async

and blocking on them.

Other options are blocked during operations async

, but the legacy driver is thoughtfully implemented, tested and supported, so blocking is done in a good way (i.e. everywhere ConfigureAwait(false)

and GetAwaiter().GetResult()

)

+10


source


You must use async operations as the driver is asynchronous and the operations are essentially asynchronous (mostly I / O, usually on a remote server).

NOT! Occam's razor! The simplest answer is usually correct. asynchronous programming is inherited more difficult to program and debug. Why use it for simple tasks.

Here is what I do to force synchronization, at least within my thread.



var c1 = collection.Find(filter);
var y = c1.ToListAsync();
y.Wait();
var w = y.Result.FirstOrDefault();

      

A great example. Why are there 4 lines of code when only one is required.

+3


source







All Articles