SoFunction
Updated on 2025-03-07

C# Serial port receives deadlock example

Recently, I am working on a client program about the high-speed rail simulation warehouse display system. In this program, we need to use serialPort to transmit data. Because the UI interface needs to be updated after each data reception is over, so Invoke is used to encapsulate the program code that updates the UI into a method, and then call it through Incoke. There is no problem with the program running, but when you execute(), the program will be deadlocked, and the entire program can't move even if it is stuck there.

I searched a lot of information online, and there are various such statements. Some say that I define a flag to receive data. If the closing program is executed, it is to make a judgment. If the data is received, close the serial port. If there is no, it will continue to execute. However, after personal testing, it is useless. Finally, when I was studying invoke, I found that there is also Begininvoke. At the same time, I also found the difference between them. Begininvoke is used to update UI data in the background without waiting, and invoke is used to update UI data in the background without waiting. After understanding the differences between the two, I realized that the reason for the deadlock of execution () is that invoke is at work. If I change it to begininvoke, there will be no deadlock problem.

Directly upload the code:

SerialPort serialPort1 = new SerialPort(“COM5”, 115200, , 8, ); //Initialize the serial port settings//Define the delegationpublic delegate void Displaydelegate(byte[] InputBuf);
Byte[] OutputBuf = new Byte[8];
public Displaydelegate disp_delegate;

//Receive data delegationdisp_delegate = new Displaydelegate(DispUI);
 += new SerialDataReceivedEventHandler(Comm_DataReceived);

//Serial port reading data processing functionpublic void Comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
{

Byte[] InputBuf = new Byte[8];

try
{
(InputBuf, 0,6); //Read the data in the buffer, and read 6 bytes of data at a time(100);
(disp_delegate, InputBuf);//disp_delegate is a defined delegate event, in which the program that modifies the UI is called in the delegate event}
catch (TimeoutException ex) //Timeout processing{
(());
}

}

//Update the UI interfacepublic void DispUI(byte[] InputBuf)
{

string str = (InputBuf);
// (str);
string strW = (0, 2);//Seave the substring of str, and start from index=0 to intercept the string with length 2.int OutStrW = (strW);
string strS = (2, 2);//Intercept str's substring, and intercept strings with length 2 starting from index=2int OutStrS = (strS);
OutstrWen = (OutStrW - 4).ToString();
 = strW;
 = (OutStrW - 4).ToString();
 = strS;
 = (OutStrS - 10).ToString();
}

The above example of () deadlock in C# serial port receiving data is all the content I share with you. I hope you can give you a reference and I hope you can support me more.