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)


            'Keep the app from freezing and allow Windows to continue processing yours applications messages.
            'I recommend you keep using the Thread.Sleep sub to keep the cpu usage down. It takes a millisecond value.
            '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

4 thoughts on “How to Timeout or Pause using Visual Basic.NET

  1. Richard Haller

    Thanks, Jason! I have been struggling for days to find or create my own subroutine to do this and finally found yours. It works like a charm! I never would have thought of your approach. I tried Thread.Sleep and it hung the program. I tried using a Timer and couldn’t find a way to get it to work the way I wanted. I didn’t know about DoEvents which is one of the keys.

    Thanks, again!


Leave a Reply

Your email address will not be published.