Set timeout to an operation

I have object obj which is 3rd party component,

// this could take more than 30 seconds
int result = obj.PerformInitTransaction(); 

I don't know what is happening inside. What I know is if it take longer time, it is failed.

how to setup a timeout mechanism to this operation, so that if it takes more than 30 seconds I just throw MoreThan30SecondsException ?


Solution 1:

You could run the operation in a separate thread and then put a timeout on the thread join operation:

using System.Threading;

class Program {
    static void DoSomething() {
        try {
            // your call here...
            obj.PerformInitTransaction();         
        } catch (ThreadAbortException) {
            // cleanup code, if needed...
        }
    }

    public static void Main(params string[] args) {

        Thread t = new Thread(DoSomething);
        t.Start();
        if (!t.Join(TimeSpan.FromSeconds(30))) {
            t.Abort();
            throw new Exception("More than 30 secs.");
        }
    }
}

Solution 2:

More simply using Task.Wait(TimeSpan):

using System.Threading.Tasks;

var task = Task.Run(() => obj.PerformInitTransaction());
if (task.Wait(TimeSpan.FromSeconds(30)))
    return task.Result;
else
    throw new Exception("Timed out");