Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 686
Anwar Chandra Avatar asked Feb 15 '10 11:02

Anwar Chandra


People also ask

How do you set a function timeout?

The setTimeout() method executes a block of code after the specified time. The method executes the code only once. The commonly used syntax of JavaScript setTimeout is: setTimeout(function, milliseconds);

What is set timeout?

setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.

What does setTimeout 0 do?

Invoking setTimeout with a callback, and zero as the second argument will schedule the callback to be run asynchronously, after the shortest possible delay - which will be around 10ms when the tab has focus and the JavaScript thread of execution is not busy.

How do I clear set timeout?

To cancel a setTimeout() method from running, you need to use the clearTimeout() method, passing the ID value returned when you call the setTimeout() method.


2 Answers

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.");         }     } } 
like image 80
Paolo Tedesco Avatar answered Sep 20 '22 03:09

Paolo Tedesco


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"); 
like image 35
Colonel Panic Avatar answered Sep 21 '22 03:09

Colonel Panic