I am completely new to C# and I have a pretty simple problem that I can't figure out. I am trying to improve an existing code that I don't fully understand.
My program connects to a device using the Serial port when pressing a "Connect" button :
private void button_Connect_Click(object sender, EventArgs e)
{
serialPort.PortName = (string)comboBox_SerialPorts.SelectedItem;
serialPort.Open();
serialPort.DataReceived += SerialPort_DataReceived;
}
The method SerialPort_DataReceived handles the DataReceived event :
public delegate void InvokeTreatment(byte[] buffer);
private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
byte[] buffer = new byte[13];
try
{
serialPort.Read(buffer, 0, buffer.Length);
byte tmp = 0;
for (int i = 1; i < 11; i++)
tmp += buffer[i];
if ((buffer[11] == tmp) && (buffer[12] == '!'))
try
{
this.BeginInvoke(new InvokeTreatment(Treatment_UART), new object[] { buffer });
}
catch { }
}
catch { }
}
The Treatment_UART is a function that uses the values from the Serial Port to display values on my interface.
private void Traitement_UART(byte[] buffer)
At this point, my program works correctly : It displays in real-time the values received from my Serial device.
I now want to do some processing in another method called "Processing" that starts when pressing a button (for example a long for loop that processes data received from the Serial device). My problem is that, during Processing execution, the real-time receiving and displaying of the Serial values is not anymore active. I need my program to keep receiving information from the Serial device during the execution of Processing.
There might be different ways to do that. I thought about running my function in another thread, or simply calling the "SerialPort_DataReceived" method inside my Processing method... How should I do that ? Maybe running Processing in another thread implies risks of reading incorrect (or not actualized) values from the Serial port ?
Thanks in advance!