Comment: This control has been used for the past few days, but there are always problems. Maybe this article is the final solution to the problem.]
The reading and writing of serial data in SerialPort are quite different. Since the serial port does not know when data will arrive, there are two methods to read data from the serial port.
1. Real-time reading of serial ports by threads;
Ii. event triggering method implementation.
Because the real-time reading of serial ports by threads is not very efficient, it is better to trigger events. There is a datareceived event in the SerialPort class. When data in the read cache of the serial port arrives, the datareceived event is triggered, in which the SerialPort. the receivedbytesthreshold attribute determines the number of data items in the serial port read cache before the datareceived event is triggered. The default value is 1.
In addition, the SerialPort. datareceived event runs in a special way. It runs in a secondary thread and cannot directly transmit data with the display data control in the main thread. It must be implemented indirectly. As follows:
SerialPort spsend; // spsend. spreceive is connected through a virtual serial port, and data can be transmitted between them. Spsend sends the data SerialPort spreceive; // spreceive accepts the textbox txtsend; // the textbox txtreceive in the sending area; // the receiving area button btnsend; // The data sending button delegate void handleinterfaceupdatedelegate (string text); // delegate, which is the focus of handleinterfaceupdatedelegate interfaceupdatehandle;
Public void initclient () // The form control is being initialized ...{
Interfaceupdatehandle = new handleinterfaceupdatedelegate (updatetextbox); // instantiate the delegate object spsend. open (); // the SerialPort object must be closed before the end of the program. datareceived + = ports. serialdatareceivedeventhandler (spreceive_datareceived );
Spreceive. receivedbytesthreshold = 1;
Spreceive. open ();
}
Public void btnsend_click (Object sender, eventargs E)
...{
Spsend. writeline (txtsend. Text );
}
Public void spreceive_datareceived (Object sender, ports. serialdatareceivedeventargs E)
...{
Byte [] readbuffer = new byte [spreceive. readbuffersize];
Spreceive. Read (readbuffer, 0, readbuffer. Length );
This. Invoke (interfaceupdatehandle, new string []... {encoding. Unicode. getstring (readbuffer )});
}
Private void updatetextbox (string text)
...{
Txtreceive. Text = text;
}