3

I need to count items that match a filter using an older controller that hasn't been switched to async. We have an async answer on how to do this:

long result = await collection.CountAsync(Builders<Hamster>.Filter.Eq(_ => _.Name, "bar"));

I also found an article Introducing the 2.0 .NET Driver on the MongodDb website that has a comment that seems to confirm that it is impossible:

  1. It's async only: That's true. There has been a trend for new APIs to be async only (e.g. Microsoft's HttpClient). In general async programming is easy and results in higher server throughput without requiring a large number of threads. We are considering whether we should also support a sync API, and while we have gotten some requests for it (yours included) in general users seem eager to use async programming.

Nonetheless, I would like to ask if there is a way to do this / a confirmation that it's impossible without making the controller method async (and all its helpers).

4
  • 1
    you should be able to run collection.CountAsync().Result without the await, it will just run synchronously. Commented Feb 4, 2016 at 21:14
  • Looks like we posted at the exact same time. Please post that as an answer so I can accept it. Copy mine if you want, I will delete mine. Commented Feb 4, 2016 at 21:15
  • 1
    no worries! as long as you got it figured out Commented Feb 4, 2016 at 21:16
  • Thanks, I appreciate the help! Commented Feb 4, 2016 at 21:18

2 Answers 2

2

Since v2.2 of the driver there are synchronous overloads for all the async methods so you should use them instead of blocking on the async API. Doing that is less performant and may lead to deadlocks:

long countOfItemsMatchingFilter = yourCollectionName.Count(yourFilterName);
Sign up to request clarification or add additional context in comments.

1 Comment

If you are running an earlier version of 2.x, see my answer.
0

Well...that was easy - I forgot you could just user .Result to bypass the whole "no await in sync methods" thing:

long countOfItemsMatchingFilter = yourCollectionName.CountAsync(yourFilterName).Result;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.