How to limit the execution time of a function in c sharp?

后端 未结 8 776
太阳男子
太阳男子 2020-12-30 03:13

I\'ve got a problem. I\'m writing a benchmark and I have a function than is either done in 2 seconds or after ~5 minutes(depending on the input data). And I would like to st

相关标签:
8条回答
  • 2020-12-30 04:07

    Use an OS callbacks with a hi performance counter, then kill your thread, if exists

    0 讨论(0)
  • 2020-12-30 04:09
    private static int LongRunningMethod()
    {
        var r = new Random();
    
        var randomNumber = r.Next(1, 10);
    
        var delayInMilliseconds = randomNumber * 1000;
    
        Task.Delay(delayInMilliseconds).Wait();
    
        return randomNumber;
    }
    

    And

    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.");
    }
    

    it work for me! Source: https://jeremylindsayni.wordpress.com/2016/05/28/how-to-set-a-maximum-time-to-allow-a-c-function-to-run-for/

    0 讨论(0)
提交回复
热议问题