learning
Active member
I set up a class with an event as shown here :
And from the main program am using this code :
When the event triggers I get an error in the program where trying to update the forms text that says "Cross-thread operation not valid: Control 'txtSONumber' accessed from a thread other than the thread it was created on."
Am I using the custom event incorrectly?
Thanks in advance for your help.
VB.NET:
Imports System.IO.Ports
Public Class CommPort
Dim _msg As String
Dim WithEvents SerialPort As New SerialPort
Public Sub New(ByVal portID As String)
If SerialPort.IsOpen Then
SerialPort.Close()
End If
Try
With SerialPort
.PortName = portID
.BaudRate = 9600
.Parity = IO.Ports.Parity.None
.DataBits = 8
.StopBits = IO.Ports.StopBits.One
End With
SerialPort.Open()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Public Event DataReceived(ByVal message As String)
Private Sub ReadData(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
Dim _bytes As Integer = SerialPort.BytesToRead
_msg = ""
For i As Integer = 0 To _bytes - 1
_msg = String.Concat(_msg, Chr(SerialPort.ReadChar))
Next
RaiseEvent DataReceived(_msg)
End Sub
End Class
And from the main program am using this code :
VB.NET:
Public Class Main
Dim WithEvents commTest As New CommPort("COM1")
Private Sub ProcessCommData(ByVal message As String) Handles commTest.DataReceived
txtSONumber.Text = message
End Sub
End Class
When the event triggers I get an error in the program where trying to update the forms text that says "Cross-thread operation not valid: Control 'txtSONumber' accessed from a thread other than the thread it was created on."
Am I using the custom event incorrectly?
Thanks in advance for your help.