VB.NET timer.Start() 循环无值



我正在尝试循环所有计时器并停止所有计时器,但正在运行的计时器除外。

法典

'Block timers
Private Sub blocktimers()
Dim i As Integer
For Each c As Timer In Me.components.Components
If TypeOf c Is Timer Then
If c.Enabled And c.Interval <> 100 Then
carray(i) = c
ReDim Preserve carray(i + 1)
c.Stop()
End If
End If
Next
End Sub
'Release timers
Private Sub releasetimers()
For Each c As Timer In carray
If c IsNot Nothing Then
c.Start()
End If
Next
End Sub

blocktimers(( 循环所有计时器,但 releasetimers(( 只循环 2 个计时器,第二个计时器值为:无

如果 blocktimers(( 循环例如 10 个计时器,则 releasetimers(( 只循环 1。

在向数组添加计时器后,您忘记递增i

carray(i) = c
ReDim Preserve carray(i + 1)
c.Stop()
i += 1 '<-- You forgot this.

此外,此行需要更改:

For Each c As Timer In Me.components.Components

这假设每个组件都是一个计时器,这意味着如果任何组件不是计时器,您的代码就会中断。

改为:

For Each c As Object In Me.components.Components

建议:

由于您使用的是动态大小的数组,因此我建议您切换到List(Of T)以省去一些麻烦:

'Our list of timers.
Dim Timers As New List(Of Timer)
Private Sub blocktimers()
'Clear the list before we start adding timers (just in case you decide to call this method multiple times).
Timers.Clear()
For Each c As Object In Me.components.Components
If TypeOf c Is Timer Then
If c.Enabled AndAlso c.Interval <> 100 Then
'Cast 'c' to a Timer and add it to the list.
Timers.Add(DirectCast(c, Timer))
c.Stop()
End If
End If
Next
End Sub
Private Sub releasetimers()
'Iterate our Timers list.
For Each c As Timer In Timers
'While possible, you can be fairly certain at this point that a timer is not null.
c.Start()
Next
End Sub

您可能已经注意到,我也使用了AndAlso而不是And。这是因为AndAlso只在左侧(c.Enabled(计算为True时才计算右侧(c.Interval <> 100(,而And将始终计算两侧。

这被称为短路,您可以在此处阅读更多信息:(OrElse 和 Or( 和 (AndAlso and And( - 何时使用?

最新更新