多个倒计时器,分别运行

时间:2017-06-15 02:55:17

标签: vb.net

我正在尝试让多个倒计时器单独工作。不是为每个倒数计时器编写代码,而是如何对它们进行分组并以简单的方式实现这一目标?

Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Timer1.Start()
End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Timer2.Start()
End Sub

Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Timer3.Start()
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Timer1.Interval = 1000
    If Val(Label1.Text) = 0 Then
        Timer1.Stop()
    Else
        Label1.Text = Val(Label1.Text) - 1
    End If
End Sub

Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Timer2.Interval = 1000
    If Val(Label2.Text) = 0 Then
        Timer2.Stop()
    Else
        Label2.Text = Val(Label2.Text) - 1
    End If
End Sub

Private Sub Timer3_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    Timer3.Interval = 1000
    If Val(Label3.Text) = 0 Then
        Timer3.Stop()
    Else
        Label3.Text = Val(Label3.Text) - 1
    End If
End Sub
End Class

2 个答案:

答案 0 :(得分:0)

只需运行一个计时器:

Public Class Form1

  Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.
    Timer1.Interval = 1000
    Timer1.Start()
  End Sub

  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Label1.Text = "10"
  End Sub

  Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Label2.Text = "20"
  End Sub

  Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Label3.Text = "30"
  End Sub


  Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    If CInt(Val(Label1.Text)) > 0 Then
      Label1.Text = (CInt(Val(Label1.Text)) - 1).ToString
    End If
    If CInt(Val(Label2.Text)) > 0 Then
      Label2.Text = (CInt(Val(Label2.Text)) - 1).ToString
    End If
    If CInt(Val(Label3.Text)) > 0 Then
      Label3.Text = (CInt(Val(Label3.Text)) - 1).ToString
    End If
  End Sub


End Class

答案 1 :(得分:0)

只需使用Microsoft的Reactive Framework(NuGet“System.Reactive”),然后就可以执行此操作:

Dim start As Func(Of Integer, Label, IDisposable) = _
    Function(n, lb)
        Return Observable _
            .Interval(TimeSpan.FromSeconds(1.0)) _
            .Take(n) _
            .Subscribe(Sub(x) lb.Text = (CLng(n) - x).ToString())
    End Function

Dim subscription1 = start(10, Label1)
Dim subscription2 = start(20, Label2)
Dim subscription3 = start(30, Label3)

就是这样。这就是所有代码。

如果Observable自然完成,则Interval计时器会自动停止。如果要在Observable完成之前停止它们,请运行以下代码:

subscription1.Dispose()
subscription2.Dispose()
subscription3.Dispose()