gpt4 book ai didi

vb.net - 两个定时器同时独立运行

转载 作者:行者123 更新时间:2023-12-04 06:09:39 25 4
gpt4 key购买 nike

首先,我只想对过去几周给予的所有帮助表示感谢。我学到了很多东西,我的程序每天为我节省了很多时间。

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

我尝试在第一个循环中嵌套第二个循环,但第二个循环需要 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 毫秒继续滴答

最佳答案

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

关于vb.net - 两个定时器同时独立运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7923217/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com