首页 > 解决方案 > 我怎样才能尽可能多地运行 Timer?[Vb.Net]

问题描述

我有 2 个文本框和 2 个计时器。我首先在 timer1 中运行它

if not textbox1.text = textbox2.text then
timer2.start
else
msgbox "finished"
end if

但是当 textbox1 等于 textbox2 时 timer1 跳过读取并且总是出错。我有机会运行 timer2 和 textbox2 一样多吗?例如,如果 textbox2 为 3,则 timer2 运行 3 次。我可以摆脱 textbox1 = textbox2 控件并运行实际上正确且不起作用的代码。请帮我。谢谢你。

标签: vb.nettimer

解决方案


我很难理解这个问题,但我知道您想多次运行某个计时器,然后在 x 次后继续运行另一个计时器。这可以使用类似这样的东西来完成(我没有测试过这段代码):

Private WithEvents Timer1, Timer2, Timer3 As New System.Timers.Timer() With {.AutoReset = False}
Private NbTimesRun As New Dictionary(Of System.Timers.Timer, Integer) From {
    {Timer1, 0},
    {Timer2, 0},
    {Timer3, 0}
}

Private Sub Timer1_Elapsed(sender as Object, e As EventArgs) Handles Timer1.Elapsed
    Debug.Print("Timer1 elapsed")
    ' Do some stuff here
    NbTimesRun(Timer1) += 1
    If NbTimesRun(Timer1) == 3 Then
        Timer2.Start()
    Else
        Timer1.Start()
    End If
End Sub

Private Sub Timer2_Elapsed(sender as Object, e As EventArgs) Handles Timer2.Elapsed
    Debug.Print("Timer2 elapsed")
    ' Do some stuff here
    NbTimesRun(Timer2) += 1
    If NbTimesRun(Timer2) == 3 Then
        Timer3.Start()
    Else
        Timer2.Start()
    End If
End Sub

等等。

但是,这是一个非常糟糕的设计模式,例如,您应该使用单个计时器,检查它运行的次数并根据该次数调用方法。定时器需要被释放,所以覆盖Dispose并调用TimerX.Dispose()


推荐阅读