Results 1 to 3 of 3

Thread: [RESOLVED] [2005] How to use the Timer or Stopwatch Class to timeout in 30 seconds

  1. #1

    Thread Starter
    Member
    Join Date
    Dec 2006
    Posts
    56

    Resolved [RESOLVED] [2005] How to use the Timer or Stopwatch Class to timeout in 30 seconds

    Hello,

    Nothing I have found on the Stopwatch Class shows how to watch for X seconds elapsed time in a piece of code. It seems to be generally used for performance measurements.

    What I'm doing is grabbing data from a serial port, which works, but it can't handle a connection that doesn't send data so I want to time out the serial port based on nothing happening for say 30 seconds.

    What I need is code that will do something like this pseudo-code:


    Do Until SerialPort.BytesToRead >= XXXX or timeOut = 1

    start stopwatch
    when 30 seconds elapses set variable timeOut = 1 'to be used in Do test
    stop stopwatch

    <other stuff here/>

    Loop


    Thanks,

    Ike
    Last edited by IkeConn; Jan 17th, 2007 at 04:22 PM. Reason: wrong class?

  2. #2
    PowerPoster stanav's Avatar
    Join Date
    Jul 2006
    Location
    Providence, RI - USA
    Posts
    9,290

    Re: [2005] How to use the Stopwatch Class to timeout in 30 seconds

    stopwatch isn't the right class for what you're trying to do. You should user a timer instead, and set its interval to 30000 (30 seconds). Then in the timer.Tick event, you set the variable timeOut.

  3. #3

    Thread Starter
    Member
    Join Date
    Dec 2006
    Posts
    56

    Re: [2005] How to use the Timer or Stopwatch Class to timeout in 30 seconds

    I ended up using a timer inside a sub that fires on a SerialPort1.PinChanged event and looks for Carrier Detect to raise. Then the code starts a timer that fires in 15 seconds (more or less) which triggers the OnBadConnectionFound sub which resets the port.



    Public Sub TimeOutBadConnection(ByVal sender As Object, _
    ByVal e As System.IO.Ports.SerialPinChangedEventArgs) _
    Handles SerialPort1.PinChanged
    Dim portTimer As New System.Timers.Timer()
    AddHandler portTimer.Elapsed, AddressOf OnBadConnectionFound
    If SerialPort1.CDHolding = True And SerialPort1.BytesToRead = 0 Then
    portTimer.Enabled = True
    portTimer.Interval = 15000
    portTimer.AutoReset = False
    GC.KeepAlive(portTimer)
    End If
    End Sub
    Public Sub OnBadConnectionFound(ByVal Source As Object, ByVal e As System.Timers.ElapsedEventArgs) ' Handles portTimer.Elapsed
    resetPort()
    End Sub

    Regards,

    Ike

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width