Good day,
Not the first time I use the SerialPort.DataReceived event, but for the first time I thought about how to use it correctly and what is hidden under it. At the moment I use the following algorithm (in order to avoid inter-stream errors):
Run the timer for a period of 10-50 msec.
1.1. In the Tick event, the data from the static variable is assigned to the desired variables. This all happens only if the flag is set, that you can check this static variable. After that, the check permission flag is reset.Triggering a DataReceived event.
2.1 If the static variable check flag is set, the command to retransmit data after 10 ms and exit the handler. Otherwise:- Reading data from the port buffer to the end of the line (ReadLine) in a static variable.
- Setting the flag to check the static variable.
First question :
What are the algorithms for receiving data on the serial port to the main stream (for example, use Invoke, but I don’t really understand this method) and, of course, with explanations, if possible?
Second question :
What other ways are there to avoid data loss besides the way I use (the command to retransmit data after a certain time)
Third question :
DataReceived event, at which moment it is called? When coming the first byte? When joining EOF?
Thank you very much!
--- UPDATE ---
Inadvertently found the use of Invoke and for some reason immediately understood everything :) What other options are there?
public delegate void AddDataDelegate(String myString); public AddDataDelegate myDelegate; private void Form1_Load(object sender, EventArgs e) { //... this.myDelegate = new AddDataDelegate(AddDataMethod); } public void AddDataMethod(String myString) { textbox1.AppendText(myString); } private void mySerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort sp = (SerialPort)sender; string s= sp.ReadExisting(); textbox1.Invoke(this.myDelegate, new Object[] {s}); }