Option Strict On Option Explicit On Public Class Form1 'Set a global FramesPerSecond variable 'As well as the threading loop so that we can abort it whenever Private fps As Double = 0 Private loop_thread As Threading.Thread Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'Startup a new thread loop_thread = New Threading.Thread(AddressOf GameLoop) End Sub Private Sub GameLoop() 'Do until we abort the thread Do Until True = False 'The "prior" time will be now Dim prior As DateTime = DateTime.Now 'This is where you'd update anything Console.WriteLine(fps.ToString) 'Lock the frames per second at 60 Call LockFps(prior, 60) Loop End Sub Private Sub LockFps(ByVal PriorTime As DateTime, ByVal TargetFps As Double) 'Get the current time this method was called Dim CurrentTime As DateTime = DateTime.Now 'The actual frames per second will be the current time we just got 'minus the prior time before we did any updating Dim ActualFps As Double = CurrentTime.Subtract(PriorTime).TotalMilliseconds 'If the target frames per second(divided by 1000 because we're working with milliseconds) 'Is less than the actual frames per second, then don't exit the sub yet If 1000 / TargetFps > ActualFps Then Call LockFps(CurrentTime, TargetFps) Else 'If the actual frames per second is greater or equal to the target, then set the variable fps = ActualFps * 1000 End If End Sub Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 'Go! Go! Go! loop_thread.Start() End Sub Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click 'Abort! Abort! Abort! loop_thread.Abort() End Sub End Class
However, after a few cycles I get a stackoverflow error on the line where I get CurrentTime in the LockFps sub. Any suggestions on how to fix it?