带有串口的vb.net中的跨线程操作无效 [英] 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)
并在类中执行此操作:
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
这就是调用这个例程:
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 行中,我收到以下错误跨线程操作无效:Control '' 从创建它的线程以外的线程访问."
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."
这仅在我使用串行端口时发生.如果我通过另一种方法输入文本,则不会出现错误.在 Microsoft 上进行一些搜索后,我发现串行端口类将在它自己的线程中运行,因此我了解单独的线程来自何处.但我不知道如何解决它.我猜我需要使用 .invoke 但我不知道需要在哪里完成.
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.
推荐答案
那是因为 DataReceived
事件是从帮助线程返回的.使用委托:
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
这篇关于带有串口的vb.net中的跨线程操作无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!