VB.NET Infinite For Loop

前端 未结 5 812

Is it possible to write an infinite for loop in VB.NET?

If so, what is the syntax?

5条回答
  •  青春惊慌失措
    2021-01-29 08:16

    Aside from all the many answers given to make a loop run forever, this may just be the first that actually uses the value of Positive Infinity to cap the loop. Just to be safe though, I included an extra option to exit after a given number of seconds so it can measure the speed of your loop.

    Sub RunInfinateForLoop(maxSeconds As Integer)
        ' Attempts to run a For loop to infinity but also exits if maxSeconds seconds have elapsed.
        Dim t As Date = Now
        Dim exitTime As Date = t.AddSeconds(maxSeconds)
        Dim dCounter As Double
        Dim strMessage As String
        For dCounter = 1 To Double.PositiveInfinity
            If Now >= exitTime Then Exit For
        Next
        strMessage = "Loop ended after " & dCounter.ToString & " loops in " & maxSeconds & " seconds." & vbCrLf &
            "Average speed is " & CStr(dCounter / maxSeconds) & " loops per second."
        MsgBox(strMessage, MsgBoxStyle.OkOnly, "Infinity Timer")
    
    End Sub
    

提交回复
热议问题