如何在c sharp中限制函数的执行时间?

Nov*_*tor 13 c# execution-time time-limiting

我有一个问题.我正在写一个基准测试,我有一个功能,而不是在2秒或大约5分钟后完成(取决于输入数据).如果执行时间超过3秒,我想停止该功能......

我该怎么做?

非常感谢!

sha*_*tap 50

嗯...,我有同样的问题,在阅读了这里的所有答案和推荐的博客之后,我为此付诸东流,

它让我执行任何带有时间限制的代码块,声明包装器方法

    public static bool ExecuteWithTimeLimit(TimeSpan timeSpan, Action codeBlock)
    {
        try
        {
            Task task = Task.Factory.StartNew(() => codeBlock());
            task.Wait(timeSpan);
            return task.IsCompleted;
        }
        catch (AggregateException ae)
        {
            throw ae.InnerExceptions[0];
        }   
    }
Run Code Online (Sandbox Code Playgroud)

并使用它来包装这样的任何代码块

    // code here

    bool Completed = ExecuteWithTimeLimit(TimeSpan.FromMilliseconds(1000), () =>
    {
         //
         // Write your time bounded code here
         // 
    });

    //More code
Run Code Online (Sandbox Code Playgroud)

  • 根据我的理解,如果它仍然在timeSpan之后运行,这将不会停止动作codeBlock.在您的基准测试场景中,如果您有多个并行运行的代码,那么应该会大大改变您的结果. (5认同)
  • 我认为您需要编写`Task task = new Task(codeBlock); task.Wait(timeSpan); task.Start(); 返回task.IsCompleted;`,因为使用您的代码,您正在启动方法并告诉它等待x次。但是实际上只分配一个任务等待并启动任务是一种更好的方法。 (2认同)

Ser*_*ier 5

最好的方法是你的函数可以经常检查它的执行时间,以决定停止它需要太长时间.

如果不是这种情况,则在单独的线程中运行该函数.在你的主线程中启动一个3秒计时器.当计时器过去时,使用Thread.Abort()终止单独的线程(当然除非函数已经结束).请参阅函数文档中的示例代码和使用前预处理.


小智 5

private static int LongRunningMethod()
{
    var r = new Random();

    var randomNumber = r.Next(1, 10);

    var delayInMilliseconds = randomNumber * 1000;

    Task.Delay(delayInMilliseconds).Wait();

    return randomNumber;
}
Run Code Online (Sandbox Code Playgroud)

var task = Task.Run(() =>
{
    return LongRunningMethod();
});

bool isCompletedSuccessfully = task.Wait(TimeSpan.FromMilliseconds(3000));

if (isCompletedSuccessfully)
{
    return task.Result;
}
else
{
    throw new TimeoutException("The function has taken longer than the maximum time allowed.");
}
Run Code Online (Sandbox Code Playgroud)

它对我有用!资料来源:https://jeremylindsayni.wordpress.com/2016/05/28/how-to-set-a-maximum-time-to-allow-ac-function-to-run-for/