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

后端 未结 8 810
太阳男子
太阳男子 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条回答
  •  梦毁少年i
    2020-12-30 03:51

    Well..., I had the same question, and after reading all the answers here and the referred blogs, I settled for this,

    It Lets me execute any block of code with a time limit, Declare the wrapper method

        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];
            }   
        }
    

    And use that to wrap any block of code like this

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

提交回复
热议问题