Run Function until true is returned OR 15 seconds has passed

Viewed 60

I have a method that needs to rerun until it either returns True or a set time period has passed. Would a cancellation token be the way to do this? A stopwatch? A timer?

    Do While partReady = False
        partReady = readTag(part, "_IO_EM_DI_04")
    Loop

Runs it until I get true returned but I need this to cancel and throw and exception or exit the loop after a given time period.

2 Answers

Use Stopwatch:

    Dim sw As New Stopwatch
    sw.Start()

    Do While partReady = False
        partReady = readTag(part, "_IO_EM_DI_04")
        If sw.Elapsed.TotalSeconds >= 15 Then
            Exit Do
        End If
    Loop

I would use a Timer here, where the contents of the loop from your question are moved to the Timer's Elapsed event. This will allow you to tune CPU use based on how often the timer ticks and help keep the loop from running away with your CPU core.

Related