在具有串行端口的vb.net中,跨线程操作无效

在具有串行端口的vb.net中,跨线程操作无效,vb.net,Vb.net,我有一个表单,它使用一个类来处理richtextbox中的传入数据。数据通过串行端口接收 加载表单时,我通过以下操作初始化类: oDigi = New DigitalProcessing oDigi.InitHostForm(Me, 1, MyParentNumber) 在类中执行此操作: Public Sub InitHostForm(ByVal theHostForm As Object, ByVal iInterface As Integer, Optional ByVal P

我有一个表单,它使用一个类来处理richtextbox中的传入数据。数据通过串行端口接收

加载表单时,我通过以下操作初始化类:

oDigi = New DigitalProcessing
oDigi.InitHostForm(Me, 1, MyParentNumber)
在类中执行此操作:

Public Sub InitHostForm(ByVal theHostForm As Object, ByVal iInterface As Integer,      Optional ByVal Parent As Integer = 0)
Hostform = theHostForm
ParentNr = Parent
End Sub
在表单中,我初始化了serialport,一切都很好。当从串行端口接收到文本时,调用此例程:

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
这就是所谓的例行程序:

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
在上面的If行中,我收到以下错误“跨线程操作无效:控件“”是从创建它的线程以外的线程访问的。”


只有使用串行端口时才会发生这种情况。如果通过另一种方法输入文本,则不会出现错误。在Microsoft上搜索时,我发现Serial port类将在它自己的线程中运行,因此我了解独立线程的来源。但我不知道如何修复它。我猜我需要使用.invoke,但我不知道需要在哪里执行。

这是因为
DataReceived
事件是从帮助线程返回的。使用代理:

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

对我只是不知道如何在这里使用.invoke