Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to use the MongoDB C# driver synchronously

I have a 2 layered C# project. The 1st one is a 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 driver non-async methods (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 with c#?

like image 307
fatihyildizhan Avatar asked Dec 06 '22 21:12

fatihyildizhan


2 Answers

EDIT: In v2.2 of the driver they are adding synchronous versions for all the async operations that are synchronous almost all the way down. If you can't use async-await for some reason this is the next best option.


You should be using the async operations as the driver is async and the operations are inherently asynchronous (being mainly I/O, usually to a remote server).

But, if you must keep things synchronous you have 3 options, ordered from the most recommended to the least:

  1. Keep using the old (v1.x) version of the driver with the synchronous API.
  2. Use the new driver, but with the legacy API (client.GetServer). It requires a different nuget package (named Legacy) and has both types of API.
  3. Use the async operations and block on them with Task.Result or Task.Wait.

The old version is preferred because it uses synchronous I/O operations which is usually better than using async ones and blocking on them.

The other options both block on async operations but the legacy driver is thoughtfully implemented, tested and maintained so the blocking is done in a good way (i.e. using ConfigureAwait(false) and GetAwaiter().GetResult() everywhere)

like image 113
i3arnon Avatar answered Dec 24 '22 14:12

i3arnon


You should be using the async operations as the driver is async and the operations are inherently asynchronous (being mainly I/O, usually to a remote server).

NO! Occam's razor! The simplest answer is typically the correct one. async programming is inheritantly more difficult to program and debug. Why be forced to use it for simple tasks.

Here is what I do to force sync at least within my own thread.

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

Perfect case in point. Why have 4 lines of code when only one is necessary.

like image 24
Ultra Avatar answered Dec 24 '22 14:12

Ultra