ActiveX Control Synchronous vs Asynchronous Comparison

The table below shows equivalent code using the asynchronous and synchronous programming models.


The synchronous model can be simpler to design and implement in most cases, however, under adverse conditions such as communications timeouts, the application's user interface can be affected.

The asynchronous model can be more complex to design and implement, however, under adverse conditions such as communications timeouts, the application's user interface is not affected.

The code example shown below is based on our Modbus/TCP ActiveX Control.


Asynchronous Code Example

' A timer is used to sequence through multiple sequential transactions. 
Private Sub Timer1_Timer()
   ' If Busy try again at next timer tick
   If ASMBTCP1.Busy = True Then Exit Sub

   Select Case ASMBTCP1.Tag
     Case 0:
       ' Idle
       Exit Sub
     Case 1:
       ' Set starting memory location for transaction
       ASMBTCP1.MemStart = "1"
     Case 2:
       ' Set starting memory location for transaction
       ASMBTCP1.MemStart = "201"
   End Select
   ' Start the transaction
   ASMBTCP1.AsyncRefresh
 End Sub


' Complete event fires when transaction has completed. At this point, transaction result should be checked and data processed if successful.
Private Sub Asmbtcp1_Complete(ByVal Result As Integer)
  'Test result
  If Result = 0 Then
    Select Case ASMBTCP1.Tag
    Case 1:
      ' Extract data
      Text1 = ASMBTCP1.DataWord(0)
      ASMBTCP1.Tag = 2
    Case 2:
      ' Extract data
      Text2 = ASMBTCP1.DataWord(0)
      ASMBTCP1.Tag = 0
    End Select
  'ERROR
  Else
    Select Case ASMBTCP1.Tag
    Case 1:
      ' Implement error handler
      ASMBTCP1.Tag = 0
    Case 2:
      ' Implement error handler
      ASMBTCP1.Tag = 0
    End Select
  End If
End Sub
      		

Synchronous Code Example

' No timer is required to sequence through multiple sequential transactions. 
Private Sub ReadRegisters()
   ' Set starting memory location for transaction 
   ASMBTCP1.MemStart = "1"
   ' Perform the transaction
   ASMBTCP1.SyncRefresh
   ' Test result
   If ASMBTCP1.Result = 0 Then 
     ' Extract data
     Text1 = ASMBTCP1.DataWord(0) 
   Else
     ' Implement error handler
  Endif

  DoEvents

  ' Set starting memory location for transaction
  ASMBTCP1.MemStart = "201"
  ' Perform the transaction
  ASMBTCP1.SyncRefresh
  ' Test result
  If ASMBTCP1.Result = 0 Then
    ' Extract data
    Text2 = ASMBTCP1.DataWord(0)
  Else
    ' Implement error handler
  Endif
End Sub