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#?
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:
client.GetServer
). It requires a different nuget package (named Legacy) and has both types of API.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)
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.
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