Set timeout to an operation

Anwar Chandra picture Anwar Chandra · Feb 15, 2010 · Viewed 77.7k times · Source

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 ?

Answer

Paolo Tedesco picture Paolo Tedesco · Feb 15, 2010

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