Mongo DB C# Driver 2.0 同步计数

Mongo DB C# Driver 2.0 Synchronous Count

我需要使用未切换到异步的旧控制器来计算与过滤器匹配的项目。我们有一个关于如何做到这一点的

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

我还在MongodDb网站上找到了一篇文章Introducing the 2.0 .NET Driver,其中的评论似乎证实了这是不可能的:

  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.

尽管如此,我想问一下是否有办法做到这一点/确认如果不使控制器方法异步(及其所有助手)是不可能的。

嗯...这很简单 - 我忘记了您可以只使用 .Result 来绕过整个 "no await in sync methods" 事情:

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

从驱动程序的 v2.2 开始,所有异步方法都有同步重载,因此您应该使用它们而不是在异步 API 上阻塞。这样做会降低性能并可能导致死锁:

long countOfItemsMatchingFilter = yourCollectionName.Count(yourFilterName);