Set timeout to an operation Set timeout to an operation multithreading multithreading

Set timeout to an operation


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


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


If you don't want to block the main thread you can use a System.Threading.Timer:

private Thread _thread;void Main(string[] args){    _thread = new ThreadStart(ThreadEntry);    _thread.Start();    Timer timer = new Timer(Timeout,null,30000,Timeout.Infinite);}void ThreadEntry(){    int result = obj.PerformInitTransaction(); }void TimeOut(object state){    // Abort the thread - see the comments    _thread.Abort();    throw new ItTimedOutException();}

Jon Skeet has a less forceful way (Shutting Down Worker Threads Gracefully) of stopping the thread than abort.

However as you're not in control of the operations PerformInitTransaction() is doing there is not much you can do from when Abort fails and leaves the object in an invalid state. As mentioned if you are able to cleanup anything that aborting the PerformInitTransaction has left hanging, you can do this by catching the ThreadAbortException, though as it's a 3rd party call it'll mean guessing the state you've left their method in.

The PerformInitTransaction should really be the one providing the timeout.