【问题标题】:How do I run a sub a certain amount of times a second until running = false?如何在运行 = false 之前每秒运行一个子程序一定次数?
【发布时间】:2014-11-16 19:52:27
【问题描述】:

我正在使用 Visual Basic,因为我很快就会在大学学习它,我想知道如何在我尝试使用 Do Loop 的同时每秒运行一定次数的子程序,同时在循环内调用函数

Do
    GameLoop()
Loop Until running = false

我也尝试过使用 while 循环,任何帮助都会很棒:D

【问题讨论】:

  • 使用计时器来调用事件。根据certain amount of times计算Interval
  • 您需要精确到何种程度,因为每秒循环数不一定是您可以准确指定的值。这主要是因为循环的潜在持续时间大于(单循环消耗时间 * 每秒循环数)。然后你必须考虑多线程和线程等待时间。
  • 您的问题标记了三种不同的语言:请选择一种
  • VBA 和 VB6 不支持多线程。请编辑您的帖子以仅包含相关的语言标签。谢谢!
  • 您可以在 VB6 中使用线程,但它并不漂亮:freevbcode.com/ShowCode.asp?ID=1287

标签: vb.net vba vb6


【解决方案1】:

如果让循环进入百分之一秒是可以接受的,那么下面的就可以了。

Dim Start As Variant
Do
  Start = Timer

  GameLoop

  Do While (Timer - Start < 0.01)
   DoEvents
  Loop
Loop Until running = False

如果需要更高的精度,请将计时器替换为:How to get time elapsed in milliseconds

如果 GameLoop 太慢,那么它将全速运行;否则它将以所需的每秒循环数运行。

如果不需要,可以删除 DoEvents,或者您不喜欢它的事件混杂副作用。

注意这是 VB6 代码,对于 VB.Net 毫秒计时器检查:How do you get the current time in milliseconds (long), in VB.Net?

【讨论】:

    【解决方案2】:

    在你的循环中放置另一个循环。

    在这个内部循环中,您等待剩余时间,如果没有剩余时间,则继续。

    我为此使用了 GetTickCount API,它使用毫秒作为输入,尽管它的准确性取决于 cpu 时钟的分辨率

    Option Explicit
    
    Private Declare Function GetTickCount Lib "kernel32" () As Long
    
    Private mblnRun As Boolean
    
    Private Sub Command1_Click()
      StartLoop
    End Sub
    
    Private Sub Command2_Click()
      StopLoop
    End Sub
    
    Private Sub StartLoop()
      Dim lngStart As Long
      mblnRun = True
      Do While mblnRun
        'store start time
        lngStart = GetTickCount
        'do your actions
        DoSomething
        'wait for the remaining time
        Do While GetTickCount < lngStart + 2000
          'wait until 2 seconds are passed since the start of this loop cycle
          DoEvents
        Loop
      Loop
    End Sub
    
    Private Sub StopLoop()
      mblnRun = False
      Caption = "Stopped : " & CStr(Now)
    End Sub
    
    Private Sub DoSomething()
      Caption = "Running : " & CStr(Now)
    End Sub
    

    只要mblnRunTrue,循环就会继续运行

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      • 2012-01-09
      • 2012-03-26
      • 2019-06-06
      • 1970-01-01
      相关资源
      最近更新 更多