Display Array into textbox Cross-thread

ejleiss

Active member
Joined
Oct 1, 2012
Messages
37
Programming Experience
1-3
I am reading bytes from a serial port and storing them in an array. I would then like to display the array contents to a textbox. I keep getting this error code --> "Cross-thread operation not valid. Control TextBox1 accessed from a thread other than the one it was created on". My code is below. what am I doing wrong?
Thanks

VB.NET:
    Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived

        While SerialPort1.BytesToRead And SerialPort1.IsOpen
            If SerialPort1.IsOpen Then
                AccelRaw = SerialPort1.ReadByte()


            End If


            If (Not oFileStream Is Nothing) Then
                If (oFileStream.CanWrite = True) Then
                    oFileStream.WriteByte(AccelRaw)
                End If
            End If


            Me.TextBox1.Text = AccelRaw


            ByteArray(BuffIndex) = AccelRaw


            BuffIndex = (BuffIndex + 1) Mod Buffsize




        End While


    End Sub
 
The SerialPort raises its DataReceived event on a secondary thread but you can only access a control on the UI thread. As such, you need to marshal a method call to the UI thread and then update your control there. Here's a thread of mine that explains the steps to do that:

Accessing Controls from Worker Threads
 
By the way, even if you could do it with multi-threading issues, what's the point of setting the Text of a TextBox in a loop? You simply going to replace the previous text over and over so, when the loop completes, you're only going to see the last value. What you should be doing is constructing a single String from the data inside the DataReceived event handler, possibly using a StringBuilder, and then assigning that one String to the Text property at the end. Even then, if you're possibly going to receive data more than once, you probably still want to append the new text to the existing text rather than replace it. In that case, call the AppendText method rather than setting the Text property.
 
Back
Top