两个定时器同时独立运行

时间:2011-10-27 22:30:23

标签: vb.net visual-studio visual-studio-2010

首先,我只想感谢过去几周给予的所有帮助。我学到了很多东西,我的课程每天都节省了我数小时的工作量。

我想稍微扩展它并添加第二个与第一个计时器并行运行的计时器,但不会受到第一个计时器的任何形状或形式的影响。

我已尝试在第一个循环中嵌套第二个循环但第二个循环需要3秒才能完成(我使用thread.sleep(3000)),所以我发现它冻结了第一个循环,直到第二个循环结束。我正在阅读系统线程(System.Timers.Timer),看起来这就是我想要的路线。

我快速写了这个例子:

这假设我添加了一个Windows计时器控件作为timer1

Option Strict On
Imports System
Imports System.Timers

Public Class form1

  Private Shared timer2 As System.Timers.Timer
  timer2 = New System.Timers.Timer
  AddHandler timer2.Elapsed, AddressOf OnTimedEvent

  Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                           Handles Button1.Click
    timer1.Interval = 1000
    timer1.enabled = true
    timer2.Interval = 5000
    timer2.Enabled = True
  End sub

  Public Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) _
                         Handles Timer1.Tick
  'code for timer1 here
  End Sub

  Private Shared Sub OnTimedEvent(source As Object, e As ElapsedEventArgs)
    'code for timer2 here
  End Sub

End Class 

这是否有意义?...再次由于thread.sleep,我无法使用timer1来引发第二轮事件。我希望上面的代码让第二个线程进入休眠状态,而windows.form.timer继续每1000毫秒滴答一次

3 个答案:

答案 0 :(得分:3)

Public Class Form1
    'a timer that fires periodically
    Dim WithEvents aTimer As New System.Threading.Timer(AddressOf TickTock, Nothing, 0, 500)
    'a stopwatch for each event
    Dim swEV1 As New Stopwatch
    Dim swEV2 As New Stopwatch
    'how long between executions
    Dim ev1Time As New TimeSpan(0, 0, 1)
    Dim ev2Time As New TimeSpan(0, 0, 5)

    'test
    Private Sub Button1_Click(sender As System.Object, _
                              e As System.EventArgs) Handles Button1.Click
        Button1.Enabled = False
        'start the test
        swEV1.Start()
        swEV2.Start()
    End Sub

    Dim ev1 As New Threading.Thread(AddressOf event1)
    Dim ev2 As New Threading.Thread(AddressOf event2)

    Private Sub TickTock(state As Object)
        If swEV1.IsRunning Then
            'check the elapsed time and run the thread when needed
            'only one thread per event is allowed to run
            If swEV1.Elapsed >= ev1Time Then
                If Not ev1.IsAlive Then
                    swEV1.Reset() 'reset the stopwatch
                    swEV1.Start()
                    ev1 = New Threading.Thread(AddressOf event1)
                    ev1.IsBackground = True
                    ev1.Start()
                End If
            End If

            If swEV2.Elapsed >= ev2Time Then
                If Not ev2.IsAlive Then
                    swEV2.Reset()
                    swEV2.Start()
                    ev2 = New Threading.Thread(AddressOf event2)
                    ev2.IsBackground = True
                    ev2.Start()
                End If
            End If

        End If
    End Sub

    Private Sub event1()
        Debug.WriteLine("EV1 " & DateTime.Now.ToString)
        Threading.Thread.Sleep(500) 'simulate work
    End Sub

    Private Sub event2()
        Debug.WriteLine("EV2 " & DateTime.Now.ToString)
        Threading.Thread.Sleep(3000) 'simulate work
    End Sub


End Class

答案 1 :(得分:0)

您可以在表单上轻松拥有两个(或更多)计时器。您似乎在窗体上有一个计时器和一个以编程方式创建的计时器。所以我给出的例子是在运行时以编程方式创建它们。

在表单中定义计时器对象:

Private Shared timer1 As System.Timers.Timer
Private Shared timer2 As System.Timers.Timer

为经过的事件定义两个处理程序:

Public Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
'code for timer1 here
end sub

Public Sub Timer2_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)
'code for timer2 here
end sub

然后在按钮单击中,您可以添加处理程序并启动计时器:

Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    'Add handlers programatically
    AddHandler timer1.Elapsed, AddressOf Timer1_Tick
    AddHandler timer2.Elapsed, AddressOf Timer2_Tick

    'Set up the timer intervals and start them
    timer1.Interval = 1000
    timer1.enabled = true
    timer2.Interval = 5000
    timer2.Enabled = True

End sub

还值得一读different types of timers available to you in .NET

答案 2 :(得分:0)

我在System.Timers.Timer上遇到过一些非常糟糕的经历。没有调用Timer-Event。

我会推荐System.Threading.Timer(另外因为据我所知,System.Timers.Timer只是Threading.Timer的包装器

以下是我通常如何实现计时器的示例

请注意,我总是使用Change-Method Once启动Timer并在Callback方法的Finally Block中重新启动它,以防止同一个Timer-Callback-Method的多个并行回调。

Public Class Form1

   Private _Timer1 As System.Threading.Timer
   Private _Timer2 As System.Threading.Timer

   Public Sub New()

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

      ' Add any initialization after the InitializeComponent() call.
      _Timer1 = New System.Threading.Timer(AddressOf Timer1_Callback)
      _Timer2 = New System.Threading.Timer(AddressOf Timer2_Callback)

   End Sub

   Private Sub Timer1_Callback(ByVal state As Object)
      Try

         'code for timer1 here

      Catch ex As Exception
         'Do your errorhandling
      Finally
         'Start with a delay. Just call the Callback once
         _Timer1.Change(1000, System.Threading.Timeout.Infinite)
      End Try
   End Sub
   Private Sub Timer2_Callback(ByVal state As Object)
      Try

         'code for timer2 here

      Catch ex As Exception
         'Do your errorhandling
      Finally
         'Start with a delay. Just call the Callback once
         _Timer2.Change(5000, System.Threading.Timeout.Infinite)
      End Try
   End Sub

   Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
      Try
         'Start with a delay. Just call the Callback once
         _Timer1.Change(1000, System.Threading.Timeout.Infinite)
         _Timer2.Change(5000, System.Threading.Timeout.Infinite)
      Catch ex As Exception
         'Do your errorhandling
      End Try
   End Sub
End Class