Falaque
Falaque

Reputation: 896

handling timeout in a long running loop

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.

Upvotes: 2

Views: 1872

Answers (1)

Marc Gravell
Marc Gravell

Reputation: 1063864

Only do that check periodically? for example:

if((i % 100) == 0) { /* check for timeout */ }

Or adjust to 1000, 10000 etc depending on how fast it needs to notice the timeout.

Upvotes: 4

Related Questions