简体   繁体   中英

Cross-thread operation not valid in vb.net with serial port

I have a form that uses a class to process incoming data in a richtextbox. The data is received via serial port.

When I load the form I initialize the class by doing this:

oDigi = New DigitalProcessing
oDigi.InitHostForm(Me, 1, MyParentNumber)

and that executes this in the class:

Public Sub InitHostForm(ByVal theHostForm As Object, ByVal iInterface As Integer,      Optional ByVal Parent As Integer = 0)
Hostform = theHostForm
ParentNr = Parent
End Sub

In the form I initialize the serialport and everything is good. When text is received from the serial port this routine is called:

Private Sub MSComm1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles MSComm1.DataReceived
    If Unloaded Then Exit Sub
    oDigi.RxComData(MSComm1.ReadExisting, Val(MyRXid))
End Sub

Thats calls this routine:

Public Sub PrintToRxWindow(ByVal sMsg As String, ByVal Index As Integer)
If Len(Hostform.rtfRX(Index).Text) > lMaxLen Then
LockWindowUpdate(Hostform.rtfRX(Index).Handle)
Hostform.rtfRX(Index).SelectionStart = 0
Hostform.rtfRX(Index).SelectionLength = 500
Hostform.rtfRX(Index).ReadOnly = False
Hostform.rtfRX(Index).SelectedText = ""
Hostform.rtfRX(Index).ReadOnly = True
LockWindowUpdate(0)
End If

In the If line above I get the following error "Cross-thread operation not valid: Control '' accessed from a thread other than the thread it was created on."

This only happens if I use the serial port. If I input text via another method then I do not get an error. Upon doing some searching on Microsoft I found that the Serial port class will run in it's own thread so I understand where the separate threads are coming from. But I do not know how to fix it. I am guessing I need to use .invoke but I can't figure out where it needs to be done.

That is because the DataReceived event is returned from a helper thread. Use a delegate:

Private Sub MSComm1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles MSComm1.DataReceived
 If Unloaded Then Exit Sub
 'lambda sub acting as delegate
 'all code inside this sub is on UI thread
 Me.Invoke(Sub()
            oDigi.RxComData(MSComm1.ReadExisting, Val(MyRXid))
           End Sub)
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM