在 C# 中,我如何为计数操作计时?

问题描述 投票:0回答:1

我们有一个方法,除其他外,它返回 MongoDb 集合中的文档计数。 当数据很多而过滤器不多时,这可能会花费非常长的时间.

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

我想以某种方式将

await collection.CountDocumentsAsync(filters, cancellationToken: cancellationToken);
包装在某种函数中,该函数将计数限制为半秒。

如果得到结果,返回它。
不是,返回

Int32.MaxValue
代替。

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

c# mongodb time limit counting
1个回答
1
投票

您可以使用有时间限制的取消令牌。使用

CancellationTokenSource
创建一个新令牌,让您指定最长持续时间。例如:

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
© www.soinside.com 2019 - 2024. All rights reserved.