我想知道我是否做这样的事情:
Private CurrentASyncSerialNumber As Integer ' Break the callback chain if it isn't totally dean
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If tmrNoSerialActivity.ElapsedTime > 2 Then
CurrentASyncSerialNumber += 1
RunASyncComms(0, CurrentASyncSerialNumber)
End If
End Sub
Private Sub RunASyncComms(State As Integer, SerialNumber As Integer)
if SerialNumber<>CurrentASyncSerialNumber then return
tmrNoSerialActivity.ResetTimer
select case State
case 0
' Some aync code involving RS232
RS232_AddCommand(Sub() RunASyncComms(1000, SerialNumber))
case 1000:
' Some aync code involving RS232
RS232_AddCommand(Sub() RunASyncComms(2000, SerialNumber))
case 2000:
' Some aync code involving RS232,
RS232_AddCommand(Sub() RunASyncComms(0, SerialNumber))
' And now we start over.
RS232_AddCommand 函数与 BeginInvoke 类似,不同之处在于它在所有计时器和绘制事件完成之前不会触发下一个命令,并且还确保之前的 RS232 异步代码已完成。
我的问题是这行递归调用它“RS232_AddCommand(Sub() RunASyncComms(1000, SerialNumber))”。这会创建一个累积且永远不会被垃圾收集器收集的闭包链吗?由于它被添加到集合中并延迟运行,我这样做安全吗?或者我会因为最终的堆栈溢出而变得更糟。
我想知道我的代码是否安全。