我们有一个方法,除其他外,它返回 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/