.net, Performance

How to set a maximum time to allow a C# function to run for

Sometimes we’d like to set a maximum time allowed for a method. One example is when our code is communicating with an external dependency which stops responding e.g. a database connection, or a piece of of hardware which freezes up.

Let’s invent a scenario to examine this further.

Say I have a long running method – this randomly takes between one and ten seconds to return an integer.

private static int LongRunningMethod()
    var r = new Random();
    var randomNumber = r.Next(110);
    var delayInMilliseconds = randomNumber * 1000;
    return randomNumber;

But also say I don’t want to wait longer than a maximum of three seconds. How can I throw a TimeoutException after waiting for three seconds?

Task.Run to the rescue

In .NET, a Task is something that you want to do. It’s possible to pass a function to the Run method of Task, which will run that function asynchronously in a separate thread, and return a Task object.

So what? Well, since a Task object is immediately returned by the Task.Run method, we can call the Task’s Wait method, and wait for three seconds for the task to complete. If it has successfully completed, this method returns true. If it hasn’t completed, it returns false. So we can test the output, and return an output depending on what we want to do.

var task = Task.Run(() =>
    return LongRunningMethod();
bool isCompletedSuccessfully = task.Wait(TimeSpan.FromMilliseconds(3000));
if (isCompletedSuccessfully)
    return task.Result;
    throw new TimeoutException("The function has taken longer than the maximum time allowed.");

This pattern can be used to improve the performance of my code – it ensures that if my application locks up for whatever reason, I know I can control the maximum length of time that it’ll lock up for.