在 C# 中从串口接收数据,同时更新 ui

Receiving data from serial port in C#, while updating ui

我的问题是如何使用来自串行端口的数据更新 ui,同时仍然更新其他 ui 组件?我试过使用后台工作者,但它似乎在数据流入时阻止了 ui。

表格图片:

我的代码是:

public partial class Form1 : Form
{

    static bool _continue;
    static SerialPort _serialPort;

    BackgroundWorker dataWorker;

    string message;

    public delegate void UpdateListboxData();





    private void buttonPortConnect_Click(object sender, EventArgs e)
    {




        // Set the read/write timeouts
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;

        _serialPort.Open();
        _continue = true;

        dataWorker = new BackgroundWorker();
        dataWorker.RunWorkerAsync();
        dataWorker.DoWork += StartDataWork;



    }


    private void StartDataWork(object sender, DoWorkEventArgs e)
    {
        Delegate del = new UpdateListboxData(DataRead);
        this.Invoke(del);
    }


    private void DataRead()
    {
        while (_continue)
        {
            try
            {
                message = _serialPort.ReadLine();

            }
            catch (TimeoutException) { }
        }
    }
}

更新 winforms UI 的方法是使用 if (control.InvokeRequired) {...} 和调用,如此处示例所示 How do I update the GUI from another thread?

您不应在调用的函数中读取数据。这会阻止您的 UI.

直接在 "DoWork" 中读取数据并仅使用数据调用委托。

或者您可以使用 SerialPort 的 DataReceived 事件。

你必须使用串行端口数据接收事件和委托

    private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {

                if (TextBox.InvokeRequired)
                    TextBox.Invoke(new myDelegate(updateTextBox));

        }
        public delegate void myDelegate();

        public void updateTextBox()
        {
            int iBytesToRead = serialPort1.BytesToRead;
            //Your Codes For reding From Serial Port Such as this:
            char[] ch = new char[?];
            serialPort1.Read(ch, 0, ?? ).ToString();
            //........

        }