I have a method which should execute within given time or it should throw 'Timeout' exception. Basically it has a long running loop. Calculating timeout in every pass of loop seems expensive:
private void DoSomethingGood(int timeoutSeconds)
{
var startTime=DateTime.Now;
int count=100000000; //some big number
for(int i=0;i<count;i++)
{
//code to to take care of timeout.
var ellapsedSeconds =(DateTime.Now-startTime).TotalSeconds;
if(ellapsedSeconds>=timeoutSeconds)
{
throw new TimeoutException("Timeout");
}
/*some more code here*/
}
}
(calling above method without other code, itself is taking more than 2 seconds, largely due to DateTime.Now statement)
Can someone suggest a better way of doing it?
I am fine with +-few-milliseconds.