是封闭安全的递归回调吗?

时间:2013-01-06 20:54:48

标签: vb.net closures

我想知道我是否做了这样的事情:

   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))”。这会创建一个积累的封闭链,永远不会被垃圾收集收集?由于它被添加到集合中并在运行时被延迟,我是否安全地这样做?或者最终堆栈溢出会让我更糟糕。

我想知道我的代码是否安全。

0 个答案:

没有答案