0

我有一个类来处理串行端口,用于从扫描仪接收数据并在串行端口缓冲区中有数据时引发事件:

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,但我不知道如何。请帮我。谢谢

4

1 回答 1

1

我过去遇到过这个问题。将 OnHaveSerialPortData 中的代码替换为:

If Label1.InvokeRequired Then Label1.Invoke(Sub() Label1.Text = Compelete_Data_Received) else Label1.Text = Compelete_Data_Received

这应该处理来自主线程或不同线程的 label1 文本更改。

于 2013-05-23T16:48:51.900 回答