Click here to Skip to main content
15,888,610 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to make a textbox to display the data that it will receive from a serial communication. However, when I run the code there is a cross-thread exception. How should I fix the code? Received_mega here was already declared as a string and it is a global variable.

What I have tried:

Private Sub DataReceived(ByVal sender As System.Object, ByVal e As SerialDataReceivedEventArgs) Handles SerialPort2.DataReceived


     Received_mega = SerialPort2.ReadExisting

     Book_CodeTextBox.Text = Received_mega

 End Sub
Posted
Updated 15-Feb-20 1:07am
v2

You should invoke the update, since the thread on which runs your handler does not seem to be the thread which created the control:
VB
Private Sub DataReceived(ByVal sender As System.Object, ByVal e As SerialDataReceivedEventArgs) Handles SerialPort2.DataReceived

     Received_mega = SerialPort2.ReadExisting

     Book_CodeTextBox.Invoke(New MethodInvoker(Sub() Book_CodeTextBox.Text = Received_mega), Nothing)

 End Sub
 
Share this answer
 
To add to what Richard correctly says: the reason you get the error is because the DataReceived Event is not handled by the original UI thread - as the documentation makes clear:
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.

When you try to access any control from a thread other than the thread on which they were created (the UI thread) you will get an error.

It is possible in VB to "work round" this by adding this to your form constructor:
VB
System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = False
But a much, much better way to do it is to use Invoke to move the Control access back to the UI thread, as explained in Richard's link.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900