How to use SerialPort in .Net using the DataReceived event?

I know that the DataReceived event is fired in the background thread. How to tell a GUI thread to display data in an event handler?

+3
source share
2 answers

This code assumes that you have already added the object SerialPortat the form level using the method port_DataReceivedattached to its event DataReceived, and that you have a label with a name label1in your form.

100% , , , , . , .

void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    SerialPort port = (SerialPort)sender;
    byte[] buffer = new byte[port.BytesToRead];
    port.Read(buffer, 0, buffer.Length);
    string data = UnicodeEncoding.ASCII.GetString(buffer);
    if (label1.InvokeRequired)
    {
        Invoke(new EventHandler(DisplayData), data, EventArgs.Empty);
    }
    else
    {
        DisplayData(data, EventArgs.Empty);
    }
}

private void DisplayData(object sender, EventArgs e)
{
    string data = (string)sender;
    label1.Text = data;
}
+1
+1

Source: https://habr.com/ru/post/1742389/


All Articles