-2

I have a problem with my code. The error is

Cross-thread operation not valid: control 'label1' accessed from a thread other than the thread it was created on

the code is

Public Class Form1

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        SerialPort1.BaudRate = 9600
        SerialPort1.PortName = "COM9"

        Try
            SerialPort1.Open()
        Catch ex As Exception

        End Try
    End Sub

    Private Sub SerialPort1_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        Dim data As String

        data = SerialPort1.ReadLine()

        Label1.Text = data
    End Sub

End Class

How do I fix it?

djv
  • 15,168
  • 7
  • 48
  • 72
  • 3
    From Docs: _The DataReceived event is raised on a secondary thread when data is received from the SerialPort object. Because this event is raised on a secondary thread, and not the main thread, attempting to modify some elements in the main thread, such as UI elements, could raise a threading exception. If it is necessary to modify elements in the main Form or Control, post change requests back using Invoke, which will do the work on the proper thread._ – Steve Jul 16 '19 at 15:40
  • 1
    Possible duplicate of [Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on](https://stackoverflow.com/questions/142003/cross-thread-operation-not-valid-control-accessed-from-a-thread-other-than-the) – djv Jul 16 '19 at 17:01

1 Answers1

1

If you need it to update right away (like, when it's used by other stuff for data)

Me.Invoke(Sub() Label1.Text = data)

otherwise BeginInvoke and it will do it on next free paint event.

CruleD
  • 1,153
  • 2
  • 7
  • 15