How to implement multi-threaded serial communication in C#?

You can implement multi-threaded serial communication in C# using the SerialPort class under the System.IO.Ports namespace.

First, create a SerialPort object and set the serial port properties such as baud rate, data bits, stop bits, and parity.

using System.IO.Ports;

SerialPort serialPort = new SerialPort();
serialPort.PortName = "COM1"; // 设置串口名称
serialPort.BaudRate = 9600; // 设置波特率
serialPort.DataBits = 8; // 设置数据位
serialPort.StopBits = StopBits.One; // 设置停止位
serialPort.Parity = Parity.None; // 设置校验位

Next, create a thread function to handle reading and writing serial port data. Within this thread function, you can utilize the ReadLine() and Write() methods of the SerialPort object to read and write data.

void SerialThreadFunc()
{
    while (true)
    {
        if (serialPort.IsOpen)
        {
            // 读取串口数据
            string data = serialPort.ReadLine();
            Console.WriteLine("Received data: " + data);

            // 写入串口数据
            serialPort.Write("Hello, SerialPort!");
        }
    }
}

Finally, create a new thread and initiate serial communication within that thread.

Thread serialThread = new Thread(SerialThreadFunc);
serialThread.Start();

By following the above steps, you can achieve multi-threaded serial communication. In the main thread, you can use the relevant methods of the SerialPort object to send data to the serial port. In the serial port thread, you can read serial port data using the ReadLine() method.

bannerAds