I have a C# app that uses a COM port. To display data, I had to use a delegate to effectuate communication between the com port and GUI threads.
The relevant code:
CODE
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
lock(this)
{
string incomingData = port.ReadExisting();
string editedData = RemoveTrailingNullChars(incomingData);
string displayText = "(" + editedData + ")\r\n";
// Uncommenting the next line results in no problems whatsoever
//string displayText = "ABCDEFGHIJK\r\n";
Debug.WriteLine(displayText);
object[] payload = new object[] { displayText };
logRichTextBox.Invoke(new DisplayDelegate(UpdateDisplay), payload);
}
}
The problem I am having is that data is getting lost/damaged. The Debug.WriteLine statement caused the following to appear in the Output window:
(S=8,P=326,D=32;)
(S=9,P=326,D=31;)
(S=10,P=325,D=33;(S=16,P=325,D=35;(S=24,P=325,D=31;)
(S=25,P=326,D=32;)
There should be a separate line for data containing S=11 through S=15.
Instead, it appears as if the delegate code wasn't reentrant, and the data for the S=16 record overwrote earlier data.
Also, notice the parentheses. There are no parentheses in the serial data stream. The only ones are in the line that sets displayText.
The lock statement was an attempt at fixing this. Didn't work.
All suggestions appreciated.