Tag Archives: timeout

How to Timeout or Pause using Visual Basic.NET

Click Star to Rate Post
1 Star2 Stars3 Stars4 Stars5 Stars (5 votes, average: 5.00 out of 5)
 

The Subroutine below will put a pause or timeout in your program for the milliseconds specified in the “howLong” parameter. A single Second (1 second) equals 1,000 (one thousand) milliseconds. I also have DoEvents and a Threading.Thread delay for the calling thread inside the loop. I recommend you keep the 1 millisecond thread timeout. You can remove the DoEvents code if you want since the messages should be easily processed and not make your app appear frozen with the Threading.Thread code. Also with the Thread delay the CPU usage will not be high by your codes timeout code.

    '
    'All you need to do is Call this Subroutine and pass how long you want the procedure to timeout
    'or pause in the "howLong" parameter with a milli-seconds value.
    'Remember 1,000 milliseconds equals 1 second.
    '
    Sub timeoutPause(ByVal howLong As Integer)

        'This sub will pause or timeout your applications code for the specified amount of milli-seconds.

        'Setup a new DateTime variable with the time in milliseconds and add the milliseconds
        'value passed in the "howLong" procedure.
        Dim timeOut As DateTime = Now.AddMilliseconds(howLong)

        Do

            'Keep the app from freezing and allow Windows to continue processing yours applications messages.
            Application.DoEvents()
            '
            'I recommend you keep using the Thread.Sleep sub to keep the cpu usage down. It takes a millisecond value.
            Threading.Thread.Sleep(1)
            '
            'Keep looping and waiting until the elasped time specified in the "howLong" parameter has expired.
        Loop Until Now > timeOut

        MsgBox("The code paused for: " & howLong.ToString & " milli-seconds")

    End Sub