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
?
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);
setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.
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.
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.
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With