시리얼 포트 (Serial Port) 통신 시 Visual Basic .NET 에서는 시리얼 통신 개체가 쓰레드를 별도 생성하는 것으로 보입니다.
그래서 DataReceived 이벤트에서 발생한 값을 TextBox 나 Label 컨트롤에 표기하려면, 크로스쓰레드 오류가 발생합니다.
따라서 아래와 같은 방법으로 구현하여야 값을 정상적으로 받아올 수 있습니다.
참고하세요.
Dim strRFID As String = ""
Private Delegate Sub MyDelegate()
Private Sub spComm_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles spComm.DataReceived
Try
strRFID = DirectCast(sender, IO.Ports.SerialPort).ReadExisting()
Dim mydlg As MyDelegate
mydlg = New MyDelegate(AddressOf inText)
Me.txtReIssueRFID.Invoke(mydlg)
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Private Sub inText()
Me.txtReIssueRFID.TextValue = strRFID
End Sub
txtReIssueRFID 는 시리얼포트 (Serial Port) 에서 읽어온 값을 표시할 TextBox 컨트롤이고,
spComm 은 폼 위에 올려놓은 시리얼포트 (Serial Port) 개체입니다.