我有一个类来处理用于从Scanner接收数据的串口,并在串口缓冲区中有数据时引发事件:
Imports System
Imports System.IO.Ports
Public Class CommManager
' Here is settings for serial port
Public Event HaveScannerData(ByVal e As String)
Private Sub ProcessDataReceived(ByVal DataReceived As String)
'This sub happens when there is data in the buffer and data is Input_String
RaiseEvent HaveScannerData(Input_String)
End Sub
End Class
然后在表单中,我想使用此事件在标签框中显示它。我用:
Private WithEvents ScannerPort As New CommManager
Private Sub OnHaveSerialPortData(ByVal Compelete_Data_Received) Handles ScannerPort.HaveScannerData
Label1.Text = Compelete_Data_Received
End Sub
问题是我收到此错误消息: 跨线程操作无效:控制从其创建的线程以外的线程访问的“Label1”。 我知道我必须使用Invoke和Delegate,但我不知道如何。请帮我。感谢
答案 0 :(得分:1)
我过去曾遇到过这个问题。用OnHaveSerialPortData替换你的代码:
If Label1.InvokeRequired Then Label1.Invoke(Sub() Label1.Text = Compelete_Data_Received) else Label1.Text = Compelete_Data_Received
这应该处理来自主线程或不同线程的label1文本更改。