我正在做一个项目,该项目需要我对外部设备生成的 5 个独立事件做出反应,然后在一定延迟后执行某些操作。这些事件通常一次发生一个,但有时可能同时发生。这是一个坏主意,如果是这样,为什么?
Imports System.Windows.Threading
Class MainWindow
Private TimerList As List(Of DispatcherTimer)
Private Sub Window_Loaded(ByVal sender As System.Object,
ByVal e As ystem.Windows.RoutedEventArgs) Handles MyBase.Loaded
TimerList = New List(Of DispatcherTimer)
'Create 5 timers for the 5 events from external device
For i As Integer = 1 To 5
TimerList.Add(
New DispatcherTimer(TimeSpan.FromSeconds(10), DispatcherPriority.Normal,
New System.EventHandler(AddressOf tmr_Tick),
Me.Dispatcher) With {.Tag = i}
)
Next
End Sub
Public Sub SomeEventFromExternalDevice(ByVal ID As Integer) 'handles...
Dim CurTimer = TimerList.Find(Function(x) x.Tag = ID)
If Not CurTimer Is Nothing Then
CurTimer.Start()
End If
End Sub
Private Sub tmr_Tick(ByVal sender As Object, ByVal e As System.EventArgs)
Dim ID = DirectCast(sender.tag, Integer)
Dim curTimer = TimerList.Find(Function(x) x.Tag = ID)
curTimer.Stop()
Select Case ID
'change something on the UI to indicate that event x timer has elapsed
End Select
End Sub
End Class