c# - 在 C# 中,如何对计数操作进行时间限制?

标签 c# mongodb time limit counting

我们有一个方法,除其他外,它返回 MongoDb 集合中的文档计数。 When there is a lot of data and not many filters, this can take an insanely long time .

事实证明,大多数时候我们实际上并不需要这个值,或者当我们这样做时它可以在合理的时间内返回(因为集合中的值较少)记录,请求有更多过滤器,或者我们已经能够预测需求并应用合适的过滤器。

我想以某种方式将 await collection.CountDocumentsAsync(filters, CancelanceToken: CancellationToken); 包装在某种函数中,将计数限制为半秒。

如果得到结果,则返回它。
不是,而是返回 Int32.MaxValue

这可能吗? 如果是这样,怎么办?

最佳答案

您可以使用有时间限制的取消 token 。使用 CancellationTokenSource 创建一个新 token 允许您指定最大持续时间。例如:

var cts = new CancellationTokenSource(TimeSpan.FromSeconds(30));

var documentCount = int.MaxValue;

try
{
    documentCount = await collection.CountDocumentsAsync(filters,
        cancellationToken: cts.Token);
}
catch(TaskCanceledException)
{
    // Or ignore this if you don't care
    Console.WriteLine("Task lasted longer than 30 seconds");    
}

// Now documentCount will be equal to int.MaxValue 
// if the operation takes longer than 30 seconds

关于c# - 在 C# 中,如何对计数操作进行时间限制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76062288/

相关文章:

c++ - 如何从 UTC 时间戳的组件(Y、M、D、h、m、s、ms)创建 system_clock::time_point

algorithm - 在在线国际象棋游戏中,如何最大程度地减少时间控制滞后的影响?

c++ - ftime() 和 time() C++ 有什么区别

c# - 无论如何使用 asp.net mvc 从 3 个图像 URL 中制作一个图像?

c# - .NET 中的字符串拆分器

Django:用于 MongoDB 的长字段 (BigIntegerField)

javascript - 如何在前端显示mongodb的内容?

c# - Xml文档可用性

c# - 如何使图钉可在 bingmap wpf 中的 map 上拖动

MongoDB : Time comparison