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

Novellizator picture Novellizator · Sep 14, 2011 · Viewed 33.4k times · Source

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 stop that function if it's executed for more than 3 seconds...

How can I do it?

Thanks a lot!

Answer

shankar_pratap picture shankar_pratap · May 11, 2012

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