Chan Cimiy
Chan Cimiy

Reputation: 31

Serial port reading automatically in C#

Here below is the very simple code for serial port reading automatically:-

public partial class MainForm : Form
    {
        public MainForm()
        {
        //
        // The InitializeComponent() call is required for Windows Forms designer support.
        //
        InitializeComponent();

        //
        // TODO: Add constructor code after the InitializeComponent() call.
        //


        serialPort1.PortName="COM11";
        serialPort1.Open();

    }
    void SerialPort1DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        rtBox.Text="Data Received\n";
    }
    void BtnReadClick(object sender, EventArgs e)
    {
        rtBox.Text += "Read click" + "\n";
    }

System.InvalidOperationException: 跨執行緒作業無效: 存取控制項 'rtBox' 時所使用的執行緒與建立控制項的執行緒不同。

English translation in Google translate from Chinese Characters "Incomplete thread job: The thread used to access the control 'rtBox' is different from the thread that establishes the control."

Simply I just want to show the message "Data receive" at Rich test box. However, whenever the data receive, there is the following exception:

Do you know why? Thanks

Upvotes: 2

Views: 772

Answers (1)

user76430
user76430

Reputation:

WinForm controls such as your rich text box can only be accessed from the main UI thread. Your serial port object is invoking the event handler from a different one.

You can change your handler to do something like this --

void SerialPort1DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    Invoke(new Action(() =>
    {
        rtBox.Text="Data Received\n";
    }));        
}

This will use Control.Invoke that will then run the inner code in the UI thread.

Upvotes: 3

Related Questions