Thursday, November 25, 2010

Implementing Timeout feature in C#

The timeout feature is a handy tool in computer programming , when the user wants to execute some code  after a specific time period . Normally the timeout feature can be acheived by the Sleep command. The following code has a sleep for 2 seconds; also note that Sleep blocks the calling thread .

if (timeout > 0 )
  Threading.Sleep(2000);


Now, what if the user wants to do a polling - there are several options like Timers, WaitforSingleObject , and many others according to your needs . The code I am providing below , also implements the timeout feature using the StopWatch class .



     int timeoutValue = 10000 ; // in milliseconds.
    Stopwatch swTimeout = new Stopwatch();
    swTimeout.Start();

    do
    {           
      Thread.Sleep(2000);  // Wait for 2 seconds
      windowhandle = GetWindowHandle(caption, criteria);
 
      if (windowhandle != IsValidWindowHandle( ) )
        break;
 
    }while (swTimeout.ElapsedMilliseconds <= timeoutValue);

    // If the stopwatch is running, stop the stopwatch 

    if(swTimeout.IsRunning)
       swTimeout.Stop( );

Hope you found this useful.

No comments :