Timeout for an operation
-
Hi, I need to implement a timeout expression. Forexample like in services there is: TCPIPServiceController.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 10)); Where it checks for 10 sec whether the service has reached a running state, else exception. What i need is a customized similar expression (one line) implementing timeout, where i need to check the state of a variable, if true then carry on else exception. I don't wish to implement standalone timers event for that...., as there are many methods in which i need to implement this. Hassles of Async programming!!!. Any help please!!! Thank You.
-
Hi, I need to implement a timeout expression. Forexample like in services there is: TCPIPServiceController.WaitForStatus(ServiceControllerStatus.Running, new TimeSpan(0, 0, 10)); Where it checks for 10 sec whether the service has reached a running state, else exception. What i need is a customized similar expression (one line) implementing timeout, where i need to check the state of a variable, if true then carry on else exception. I don't wish to implement standalone timers event for that...., as there are many methods in which i need to implement this. Hassles of Async programming!!!. Any help please!!! Thank You.
I believe the
System.Threading.Timer
class should be able to handle this in relatively little code. This version of theTimer
class takes aTimerCallback
delegate that it will invoke after the specified amount of time has transpired. You can also configure it via one of the constructor overloads to continue running at a certain interval, or you can have it run only a single time. Last, it takes a stateobject
so you can pass in some data pertaining to the operation you wish to check and thatobject
will be passed in to your delegate. Here's some example code just to illustrate how easy it is to use.using System.Threading;
...private Timer _operationTimeout = null;
private void CheckOperation(MyOperationData data, int timeout)
{
// run this timer a single time...
_operationTimeout = new Timer(new TimerCallback(CheckValue), data, timeout, Timeout.Infinite);
}
// this method will be called by the timeout timer, once the interval has elapsed
private void CheckValue(object data)
{
MyOperationData opData = (MyOperationData)data;
// check the result, if it is not the expected value throw the timeout exception
if (!opData.Value.Equals(opData.ExpectedValue))
throw opData.TimeoutException;
}Hold on a second here... Don't you think you might be putting the horse ahead of the cart?